简体   繁体   English

在CSV文件中编写Python字典

[英]Write a Python dictionary inside a CSV file

I would like to write a Python dictionary inside a CSV file. 我想在CSV文件中编写Python字典。 My code is: 我的代码是:

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)

But instead of getting: 但是没有得到:

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

I have inside my CSV file: 我的CSV文件中包含以下内容:

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

Any suggestion please? 有什么建议吗?

Instead of the dictionary name, you should call the .values() method 您应该调用.values()方法,而不要使用字典名称。

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

As an example: 举个例子:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM