I would like to write a Python dictionary inside a CSV file. 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:
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
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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.