我正在尝试调整从csv文件导入到python字典中的数据。 (我用过java.util.logging.level
。)我认为DictReader创建了一个嵌套的字典,每个子字典在csv文件中都是一行。
我试图遍历每一行,更改与某些列名称键相对应的值。
我尝试将其键入为csv.DictReader()
,但这给了我一个错误:generator_units_dict[row][self.fom_cost_column] = whatever_calculation
'DictReader' object is not subscriptable
在此之后,当我运行类似
def adjust_generator_data(self, generator_units_dict):
for row in generator_units_dict:
row[self.fom_cost_column] = str(float(row[self.fom_cost_column])*1000)
row[self.fom_other_cost_column] = str(float(row[self.fom_other_cost_column])*1000)
row[self.fuel_cost_column] = str(float(row[self.fuel_cost_column])* float(row[self.heat_rate_column])/1000)
return generator_units_dict
我希望得到:
for row in generator_units_dict:
print(row)
但是控制台上不会返回错误或数据。
答案 0 :(得分:1)
由于DictReader是生成器,因此自定义它的函数也应该是生成器。
示例:
test.csv
a,b,c
1,.01,2
2,.02,3
3,.03,4
test.py
import csv
def customize(generator):
for row in generator:
row['a'] = int(row['a'])
row['b'] = float(row['b']) * 100
row['c'] = int(row['c'])
yield row
with open('test.csv',newline='') as f:
r = customize(csv.DictReader(f))
for row in r:
print(row)
输出:
OrderedDict([('a', 1), ('b', 1.0), ('c', 2)])
OrderedDict([('a', 2), ('b', 2.0), ('c', 3)])
OrderedDict([('a', 3), ('b', 3.0), ('c', 4)])