[英]Convert list of dicts to CSV
I'm trying to convert this list of dicts to csv, first of all my data is contained in a Counter
dictionnary, but since it's like a dict, I figured it would be the same thing as a dict when it comes to using it. 我正在尝试将此字典列表转换为csv,首先我的数据包含在
Counter
字典中,但是由于它像字典,因此我认为使用它与字典是一样的。 So this is what I do : 所以这就是我要做的:
My counter dict looks like this : 我的反对意见是这样的:
counterdict = {1:Counter({u'a':1, u'b':1, u'c':3}),2:Counter({u'd':1, u'f':4, u'e':2})...}
I convert it to a list of dicts like this : 我将其转换为像这样的字典列表:
new_dict = [dict(d,Month=k) for k, d in counterdict.iteritems()]
to get : 要得到 :
new_dict = [{Month :1, u'a':1, u'b':1, u'c':3}, {Month : 2,u'd':1, u'f':4, u'e':2}...]
Then I want to convert new_dict data to csv : 然后我想将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()
But I get the error : 但是我得到了错误:
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
Help please!! 请帮助!!
Edit: 编辑:
allFields
comes from counterdict
values like this : allFields
来自counterdict
这样的价值观:
allFields = list(set().union(*counterdict.values()))
So this gives me a list of all fields of counterdict. 因此,这给了我所有反驳领域的清单。
You set the fieldnames
argument to None
; 您将
fieldnames
参数设置为None
; you need to make sure allFields
is an ordered sequence of strings instead. 您需要确保
allFields
是字符串的有序序列。
Demo illustrating the problem: 演示问题的演示:
>>> 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'})
This task is a nice opportunity to use a library, such as pandas , which is built to work automatically with lists of dicts. 这个任务是使用诸如pandas之类的库的绝好机会,该库可自动处理字典列表。 Do:
做:
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.