2017-07-19 87 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