将字典列表转换为CSV

3 投票
2 回答
1590 浏览
提问于 2025-04-17 22:49

我正在尝试把这个字典列表转换成CSV格式。首先,我的数据是放在一个Counter字典里的,但因为它看起来和普通字典差不多,所以我想用起来应该也没什么区别。于是我这样做:

我的计数器字典长这样:

 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}...]

接着,我想把这个新的字典数据转换成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()))

所以这给了我一个包含所有计数器字典字段的列表。

2 个回答

2

这个任务是一个很好的机会,可以使用一个叫pandas的库。这个库专门设计用来自动处理字典列表。你只需要这样做:

import pandas as pd
df = pd.DataFrame(list_of_dicts)
df = df.set_index("first_column")
df.to_csv("filename")
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'})

撰写回答