在csv文件中排列字典中的键和值 - Python

时间:2015-03-08 15:16:15

标签: python csv dictionary

我的字典看起来像这样:

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']

1 个答案:

答案 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']