繁体   English   中英

将字典列表转换为CSV

[英]Convert list of dicts to CSV

我正在尝试将此字典列表转换为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}...]

然后我想将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()))

因此,这给了我所有反驳领域的清单。

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

这个任务是使用诸如pandas之类的库的绝好机会,该库可自动处理字典列表。 做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM