[英]How to convert a list of dictionaries to CSV format in Python, assuming the dictionaries can have different keys?
我有一個這樣的詞典列表:
[
{'item1':'bla', 'item2':'bli', 'item3':'blu'},
{'item1':'love', 'item3':'python'}
]
請注意,dict 2沒有鍵'item2'。 我想生成一個csv輸出,所以我可以將所有內容插入到SQL表中:
item1,item2,item3
bla,bli,blu
love,,python
如果所有詞典共享相同的鍵,我找到了一種簡單的方法,但如果不是這樣的話,我不會看到如何優雅地做到這一點。
將csv.DictWriter
與fieldnames
和restval
參數一起使用。
就像是
#Create a master list of keys
allKeys = ()
for row in YourListHere:
allKeys.union(row.keys())
#Sort the keys
allKeys = list(allKeys).sorted()
#Go through printing the rows
for row in YourListHere:
values = []
for key in allKeys:
#Add the values if it exists, if no key in this row add a blank
if key in row:
values.append(row[key])
else:
values.append('')
print ','.join(values)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.