2011-09-07 32 views
0

我有這樣的詞典列表:如何在Python中將字典列表轉換爲CSV格式,假設字典可以具有不同的鍵?

[ 
{'item1':'bla', 'item2':'bli', 'item3':'blu'}, 
{'item1':'love', 'item3':'python'} 
] 

注意,快譯通2沒有鑰匙「ITEM2」。 我想產生一個CSV輸出正因爲如此,所以我可以將一切都變成SQL表:

item1,item2,item3 
bla,bli,blu 
love,,python 

我發現了一個簡單的方法來做到這一點,如果所有詞典共享同一個密鑰,但我沒有看到如果情況並非如此,那麼如何優雅地做到這一點。

回答

0

喜歡的東西

#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) 
+0

謝謝你,它的工作就像一個魅力。正是我需要的 – Xavier

+0

爲什麼你會在'csv.DictWriter'爲你做這件事的時候自己做這件事?看到我的答案。 –

+0

可能只是因爲我提出了示例代碼。您的答案需要查找語法。我沒有使用csv庫,但它看起來可能是一個很好的解決方案。 – Hunter

相關問題