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

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -