将字典列表转换为CSV格式

2024-10-01 09:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将这个dict列表转换成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})...}

我把它转换成这样的一个dicts列表:

^{pr2}$

获得:

new_dict = [{Month :1, u'a':1, u'b':1, u'c':3}, {Month : 2,u'd':1, u'f':4, u'e':2}...]

然后我要将新的数据转换为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()))

所以这给了我一个反口述所有字段的列表。在


Tags: csvin列表newforcounteroutdict
2条回答

这个任务是一个很好的机会来使用一个库,比如pandas,它是为自动处理dict列表而构建的。执行:

import pandas as pd
df = pd.DataFrame(list_of_dicts)
df = df.set_index("first_column")
df.to_csv("filename")

您将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'})

相关问题 更多 >