我的字典看起来像这样:
dictionary = {'Alice': ['10', '10'], 'Tom': ['9', '8'], 'Ben': ['10', '9']}
我使用以下代码使用此词典创建了一个csv文件。改编自上一篇文章(How do I write a Python dictionary to a csv file?):
with open('test.csv', 'w') as file:
writer = csv.DictWriter(file, dictionary.keys(), lineterminator="\n")
writer.writeheader()
writer.writerow(dictionary)
这将创建一个如下所示的csv文件:
Alice, Tom, Ben
['10', '10'], ['9', '8'], ['10', '9']
但我想创建一个如下所示的csv文件:
Alice, ['10', '10']
Tom, ['9', '8']
Ben, ['10', '9']
答案 0 :(得分:0)
你需要循环你的字典项目,然后写下它们:
dictionary = {'Alice': ['10', '10'], 'Tom': ['9', '8'], 'Ben': ['10', '9']}
import csv
with open('eggs.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',')
for item in dictionary.items():
spamwriter.writerow(item)
结果:
Ben ['10', '9']
Alice ['10', '10']
Tom ['9', '8']