我正在尝试调整从csv文件导入到python字典中的数据。 (我使用了csv.DictReader()
。)我认为DictReader创建了一个嵌套的字典,每个子字典在csv文件中都是一行。
我试图遍历每一行,更改与某些列名称键对应的值。
我尝试将其键入为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)
我期望得到:
OrderedDict([('unity', '10'), ('regiony', '1'), ('capmwy', '1250'), ('fuelcosty', '26.851743334570003'), ('vomcosty', '2.17'), ('fomcosty', '30240.0'), ('vothery', '0'), ('fothery', '0.0'), ('heatratey', '7237.666667'), ('so2ratey', '0'), ('noxratey', '0.0730304'), ('availy', '0.8'), ('rmcfy', '1'), ('planttype1y', 'CC'), ('reg512y', 'NY_Z_J'), ('gwhty', '20408.04518'), ('gwhsy', '9543.262571'), ('tbtuty', '145.7268107'), ('unitcodey', '1'), ('winteravy', '0.8'), ('wshldravy', '0.8'), ('summeravy', '0.8'), ('noxmtonty', '1.064248685'), ('fuelsy', 'GA DZ')])
orderedDict([('unity', '11'), ('regiony', '1'), ('capmwy', '1250'), ('fuelcosty', '26.851743334570003'), ('vomcosty', '2.17'), ('fomcosty', '30240.0'), ('vothery', '0'), ('fothery', '0.0'), ('heatratey', '7237.666667'), ('so2ratey', '0'), ('noxratey', '0.0730304'), ('availy', '0.8'), ('rmcfy', '1'), ('planttype1y', 'CC'), ('reg512y', 'NY_Z_J'), ('gwhty', '20408.04518'), ('gwhsy', '9543.262571'), ('tbtuty', '145.7268107'), ('unitcodey', '1'), ('winteravy', '0.8'), ('wshldravy', '0.8'), ('summeravy', '0.8'), ('noxmtonty', '1.064248685'), ('fuelsy', 'GA DZ')])
但是错误和数据都不会在控制台上返回。
最佳答案
由于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)])
关于python - 在csv.DictReader类型中更改字典键的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56262920/