182

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?

0

2 Answers 2

282

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", newline="") as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2

As noted in the comments, we use newline="" as the CSV writer does its own newline management, and therefore we disable the built-in management in open(), as noted in the docs.

Sign up to request clarification or add additional context in comments.

4 Comments

Small addition: You can easily print a subset of a dict by using csv.DictWriter(f, ["testing"], extrasaction='ignore')
This approach produces a blank row between headers and values for me.
@MrChadMWood I can't reproduce that testing it now. Are you on Windows and getting \r\n and something is treating that as two newlines? If so you can try adding newline="" to the open() call to get just \n, if that is what you want (see stackoverflow.com/questions/3348460/…).
@GarethLatty open('mycsvfile.csv', 'w', newline='') worked! I am on windows. It seems like the open functionality has its own implementation for newlines, as well as csv.DictWriter. Combining them produces two newlines for each newline. More info: stackoverflow.com/a/3191811/18150609
129

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','w') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

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','w') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

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).

4 Comments

If I want to write keys in one column and values in another what should I do, I tried searching python csv docs but it seems it doesnt have writecolumn() function
@AnuragSharma the first code block does what you require.
The first block is what I'm looking for, except for some reason it's writing a blank line between each row. Any idea why?
Found an answer: stackoverflow.com/questions/3348460/…. It's Python 3 specific. The open call has to look like open('my.csv', 'w', newline='')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.