Reputation: 43
I am trying to write a dictionary of lists to a CSV file. I would like the keys to be the header of the CSV file, and the values associated with each key in the column associated with that key. if my dictionary is:
{'600': [321.4, 123.5, 564.1, 764.1], '300': [12.7, 154.7, 327.5, 894.4], 'Position': [1,2,3,4]}
I have tried to use csv.DictWriter as below:
import csv
outputFile=open('chan_press_prof.csv','wb')
dictPress={'600': [321.4, 123.5, 564.1, 764.1], '300': [12.7, 154.7, 327.5, 894.4], 'Position': [1,2,3,4]}
fields=['Position','300','600']
writeFile = csv.DictWriter(outputFile, fieldnames=fields)
writeFile.writeheader()
writeFile.writerow(dictPress)
outputFile.close()
But I get a mess:
Position,300,600 "[1, 2, 3, 4]","[12.7, 154.7, 327.5, 894.4]","[321.4, 123.5, 564.1, 764.1]"
I tried to follow the recommendations from: Dictionary of Lists to CSV in Python . That is closer, but doesn't work because the columns are in the wrong order:
code:
import csv
import StringIO
from itertools import izip_longest
outputFile=open('chan_press_prof.csv','wb')
dictPress={'600': [321.4, 123.5, 564.1, 764.1], '300': [12.7, 154.7, 327.5, 894.4], 'Position': [1,2,3,4]}
fields=['Position','300','600']
rows=izip_longest(*dictPress.values())
buf=StringIO.StringIO()
writeFile=csv.writer(outputFile)
writeFile.writerow(fields)
writeFile.writerows(rows)
outputFile.close()
And output: Position,300,600 12.7,1,321.4 154.7,2,123.5 327.5,3,564.1 894.4,4,764.1
Note that the position values (1,2,3,4) are not in the right column.
Any help is appreciated!
Upvotes: 4
Views: 4411
Reputation: 380
I wanted to do the same thing and this is what worked for me. Using the zip with the * operator did the trick for me. Also paying attention to the writerow singular and writerows plural helped write the dictionary into the kind of file I wanted with headers.
zd = zip(*dictionary.values())
with open('file.csv', 'w') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(dictionary.keys())
writer.writerows(zd)
Output looks like this,
gender,age,state,race,weights,educ
1,39,32,06,0.57,8
2,35,33,06,0.93,5
1,39,11,06,0.83,5
Your example should work exactly the same only change dictionary to be the dictionary with your data in it.
Upvotes: 4