python - Writing dict of lists to csv, specifing column order -
i doing following:
import csv d={'a':(1,2,3), '2':(4,5,6), '3':(7,8,9)} csv_file = open('test.csv','w') writefile = csv.writer(csv_file) writefile.writerow(d.keys()) open('test.csv', "wb") outfile: writer = csv.writer(outfile) writer.writerow(d.keys()) writer.writerows(zip(*d.values())) this leads .csv file can process further tools. unfortunately dict not contain order concerning keys. 1 of theses lists inside dict contains time values. prefer have list @ first in csv. order of other columns dont care. have no idea how can realise functionality.
thanks in advance
the collections package contains ordereddict class guarantees order of keys , values same when access them when created them. this:
from collections import ordereddict d = ordereddict([('a', (1,2,3)), ('2', (4,5,6)), ('3', (7,8,9))]) ...rest of code... note ordereddict constructed using list of tuples rather dictionary. because need guarantee order write keys , values in preserved.
Comments
Post a Comment