[python] How do I write a Python dictionary to a csv file?

I have what I think should be a very easy task that I can't seem to solve.

How do I write a Python dictionary to a csv file? All I want is to write the dictionary keys to the top row of the file and the key values to the second line.

The closest that I've come is the following (that I got from somebody else's post):

f = open('mycsvfile.csv','wb')
w = csv.DictWriter(f,my_dict.keys())

The problem is, the above code seems to only be writing the keys to the first line and that's it. I'm not getting the values written to the second line.

Any ideas?

This question is related to python dictionary

The answer is

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())

Which produces: