Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble writing a dictionary to csv with keys as headers and values as columns

I have a dictionary that looks like:

mydict = {"foo":[1,2], "bar":[3,4], "asdf":[5,6]}

I'm trying to write this to a CSV file so that it looks like:

foo,bar,asdf
1,3,5
2,4,6

I've spend the last hour looking for solutions, and the closest one I found suggested doing something like this:

headers = mydict.keys()
with open("File2.csv","w") as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(zip(mydict.values())

This writes the headers ok, but not the values. Here is my output:

foo,bar,asdf
[1,2]
[3,4]
[5,6]

How do I get to the output I need? I'd really appreciate some help. Thank you

like image 654
Pooja_Parthasarathy Avatar asked Sep 17 '25 10:09

Pooja_Parthasarathy


1 Answers

Instead of zip(mydict.values()), use zip(*mydict.values()). Here is the difference:

>>> zip(mydict.values())
[([1, 2],), ([3, 4],), ([5, 6],)]
>>> zip(*mydict.values())
[(1, 3, 5), (2, 4, 6)]

Basically the second version does the same thing as zip([1, 2], [3, 4], [5, 6]). This is called Unpacking Argument Lists in the docs.

To enforce a sort, use the following:

>>> zip(*([k] + mydict[k] for k in sorted(mydict)))
[('asdf', 'bar', 'foo'), (5, 3, 1), (6, 4, 2)]

This includes the headers, so just pass this into writerows() and remove your writerow() call for the headers.

Of course you can provide a key argument to the sorted() function there to do any sorting you like. For example to ensure the same order as you have in the question:

>>> order = {'foo': 0, 'bar': 1, 'asdf': 2}
>>> zip(*([k] + mydict[k] for k in sorted(mydict, key=order.get)))
[('foo', 'bar', 'asdf'), (1, 3, 5), (2, 4, 6)]
like image 133
Andrew Clark Avatar answered Sep 19 '25 06:09

Andrew Clark