4

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

3 Answers3

9

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)]
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

Also, without using csv:

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

with open("File2.csv","w") as f:
    f.write(",".join(mydict.keys()) + "\n")
    for row in zip(*mydict.values()):
        f.write(",".join(str(n) for n in row) + "\n")
    f.close()
pestrella
  • 9,786
  • 4
  • 39
  • 44
0

Did you use tablib?

I usually use tablib for this use. Its pretty simple to use: https://pypi.python.org/pypi/tablib/0.9.3

http://docs.python-tablib.org/en/latest/api/

GodMan
  • 2,561
  • 2
  • 24
  • 40