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!