我试图将这个词典列表转换为csv,首先我的数据包含在Counter
词典中,但由于它像dict一样,我认为它会是在使用它时,与dict相同。所以这就是我的工作:
我的反击字典看起来像这样:
counterdict = {1:Counter({u'a':1, u'b':1, u'c':3}),2:Counter({u'd':1, u'f':4, u'e':2})...}
我把它转换成这样的词典列表:
new_dict = [dict(d,Month=k) for k, d in counterdict.iteritems()]
得到:
new_dict = [{Month :1, u'a':1, u'b':1, u'c':3}, {Month : 2,u'd':1, u'f':4, u'e':2}...]
然后我想将new_dict数据转换为csv:
out_path= "outfile.csv"
out_file = open(out_path, 'wb')
new_dict = [dict(d,Month=k) for k, d in counterdict.iteritems()]
writer = DictWriter(out_file, fieldnames=allFields, dialect='excel')
for row in new_dict:
writer.writerow(row)
out_file.close()
但我收到错误:
Traceback (most recent call last):
File "C:/wamp/www/metrics1/script/cgi/translate_parameters.py", line 333, in <module>
writer.writerow(row)
File "C:\Python27\lib\csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Python27\lib\csv.py", line 141, in _dict_to_list
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
TypeError: argument of type 'NoneType' is not iterable
请帮助!!
编辑:
allFields
来自counterdict
这样的值:
allFields = list(set().union(*counterdict.values()))
所以这给了我一份反驳所有领域的清单。
答案 0 :(得分:3)
您将fieldnames
参数设置为None
;你需要确保allFields
是一个有序的字符串序列。
说明问题的演示:
>>> from cStringIO import StringIO
>>> import csv
>>> w = csv.DictWriter(StringIO(), fieldnames=None)
>>> w.writerow({'foo':'bar'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/lib/python2.7/csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "/opt/lib/python2.7/csv.py", line 141, in _dict_to_list
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
TypeError: argument of type 'NoneType' is not iterable
>>> w = csv.DictWriter(StringIO(), fieldnames=['foo'])
>>> w.writerow({'foo':'bar'})
答案 1 :(得分:1)
此任务是使用库的好机会,例如 pandas ,它可以自动使用dicts列表。做:
import pandas as pd
df = pd.DataFrame(list_of_dicts)
df = df.set_index("first_column")
df.to_csv("filename")