Feathyr
Feathyr

Reputation: 33

Writing dict of lists to csv, specifing column order

i am doing the 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())

with open('test.csv', "wb") as outfile:
   writer = csv.writer(outfile)
   writer.writerow(d.keys())
   writer.writerows(zip(*d.values()))

this leads to a .csv file i can process with further tools. Unfortunately a dict does not contain any order concerning the keys. One of theses lists inside the dict contains time values. I would prefer to have this list at first in the csv. About the order of the other columns i dont care. But i have no idea how i can realise this functionality.

Thanks in Advance

Upvotes: 3

Views: 611

Answers (3)

franciscod
franciscod

Reputation: 1000

The Python dict keys are sorted by its hash. If you want further info on this you can check this awesome video from PyCon 2010: https://www.youtube.com/watch?v=C4Kc8xzcA68


You can sort the keys into a list, and then access the values with that list:

sorted_keys = sorted(d.keys()) # use this instead of d.keys()
sorted_values = (d[k] for k in sorted_keys) # use this instead of d.values()

Upvotes: 0

Ken
Ken

Reputation: 226

You can create ordered dictionaries if you need to remember the order of your key - value pairs.

https://docs.python.org/2/library/collections.html#ordereddict-objects

Upvotes: 2

Brett Patterson
Brett Patterson

Reputation: 226

The collections package contains an OrderedDict class that guarantees the order of the keys and values will be the same when you access them as when you created them. So you could do something like this:

from collections import OrderedDict
d = OrderedDict([('a', (1,2,3)), ('2', (4,5,6)), ('3', (7,8,9))])
...rest of your code...

Note that the OrderedDict is constructed using a list of tuples rather than a dictionary. This is because we need to guarantee that the order we write the keys and values in is preserved.

Upvotes: 1

Related Questions