簡體   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