将字典写入csv,每个值一行

时间:2016-08-04 09:02:50

标签: python file csv dictionary key

我对Python很陌生,所以请原谅我这是一个非常基本的问题。我有一个像这样的Python字典:

foo = {'bar1':['a','b','c'], 'bar2':['d','e']}

我想将其写入csv文件,每个一行,并将键作为每行的第一个元素。输出将是(无论引号):

bar1,'a'
bar1,'b'
bar1,'c'
bar2,'d'
bar2,'e'

我试过这个such as suggested here

import csv
with open('blah.csv', 'wb') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in foo.items():
       writer.writerow([key, value])

但是这会给出以下输出,每个一行:

bar1,"['a', 'b', 'c']"
bar2,"['d', 'e']"

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

这是因为[key, value]包含多个"值"在value内。尝试迭代字典,如下所示:

for key, values in foo.items():
    for value in values:
        writer.writerow([key, value])