2017-07-19 45 views
-1

我有這樣詞典(鍵:[數組]):打印陣列以CSV

{'[email protected]': ['BMW', 'Dodge'],'[email protected]': ['Mercedes']} 

和我想打印這對CSV和使一列的數組中的每個元素,所以結果應該像(標頭是可選的):

Owner,Car_1,Car_2 
[email protected], BMW, Dodge 
[email protected], Mercedes 

謝謝!

+0

可能的答案https://stackoverflow.com/questions/3086973/how-do-i -convert-this-list-of-dictionaries-to-a-csv-file-python –

+0

同時檢查https://stackoverflow.com/questions/8331469/python-dictionary-to-csv –

回答

1

使用python csv模塊。

import csv 

d = {'[email protected]': ['BMW', 'Dodge'],'[email protected]': ['Mercedes']} 

with open('Cars.csv', 'w', newline='') as csvfile: 
    spamwriter = csv.writer(csvfile, delimiter=',') 
    spamwriter.writerow(['Owner', 'Car_1', 'Car_2']) 
    for k, v in d.items(): 
     spamwriter.writerow([k] + v) 

enter image description here

+0

非常感謝! :) – skutik

+0

只是,我不知道爲什麼,但CSV輸出每隔一秒就有空行.. – skutik

+0

與https://hastebin.com/分享你的字典 – Rahul

1

您可以使用csv.writer,假設你的數據存儲在字典d

import csv 

with open('output.csv', 'w') as fp: 
    writer = csv.writer(fp) 
    writer.writerow(['Owner','Car_1','Car_2']) 
    for key, val in d.items(): 
     writer.writerow([key] + val) 
+0

非常感謝! :) – skutik