How do I write a Python dictionary to a csv file?

CraigP picture CraigP · Apr 29, 2012 · Viewed 303.6k times · Source

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())
w.writerows(my_dict)
f.close()

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?

Answer

Gareth Latty picture Gareth Latty · Apr 29, 2012

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', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2