我有这样的字典(关键字:[数组]):
{'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']}
我想将其打印到CSV并为数组的每个元素创建一列,因此结果应该是(标题是可选的):
Owner,Car_1,Car_2
person1@gmail.com, BMW, Dodge
person2@gmail.com, Mercedes
谢谢!
答案 0 :(得分:1)
使用python csv
模块。
import csv
d = {'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['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)
答案 1 :(得分: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)