在CSV文件中写一个Python字典

时间:2014-08-20 11:39:26

标签: python csv dictionary

我想在CSV文件中写一个Python字典。 我的代码是:

import csv
cluster = {}

cluster['cluster0'] = [0,'value1','value2','value3']

cluster['cluster1'] = [1,'value1','value2','value3']

csvfile2 = "//home/tom/Desktop/cluster.csv"

with open(csvfile2, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(cluster)

但不是得到:

0,value1,value2,value3
1,value1,value2,value3

我的CSV文件中有:

c,l,u,s,t,e,r,0
c,l,u,s,t,e,r,1

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您应该调用.values()方法

,而不是字典名称
with open(csvfile2, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(cluster.values())

举个例子:

d = {1: [1,2,3], 2: [4,5,6]}

>>> d.keys()
[1, 2]

>>> d.values()
[[1, 2, 3], [4, 5, 6]]