4

I want to write a specific python dictionary to csv with header. I have looked at other questions but none of them have the similar dictionary structure as mine:

myDic = { "a" : 1, "b" : 2, "c" : 15}

header = ["word", "count"]

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    w = csv.DictWriter(f, header)
    w.writeheader()
    w.writerow(myDic)

What I got is only word,count in my CSV file. I am using python 3.

0

3 Answers 3

11

You are trying to write the entire dictionary as a row. Instead, write each row separately.

Please see here for more details:

https://docs.python.org/3/library/csv.html#csv.DictWriter

As an example please see the following usage:

import csv

myDic = { "a" : 1, "b" : 2, "c" : 15}
with open('myFile.csv', 'w', newline='') as csvfile:
    fieldnames = ['word', 'count']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for key in myDic:
        writer.writerow({'word': key, 'count': myDic[key]})

Let me know if this helps. I didn't test the code... but I may before you see the answer.

Edit Yeah tested, seems to work fine. Best of luck!

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

2 Comments

Hi, this works ok except my csv has empty lines between rows
"has empty lines between rows" - Well, that's odd. Did you include newline='' as specified in Tr1gZer0's answer?
4

This should work

import csv

myDic = { "a" : 1, "b" : 2, "c" : 15}

header = ["word", "count"]

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    writer = csv.writer(f)
    writer.writerow(header) # write the header
    for k,v in myDic.items():
        writer.writerow([k,v])

4 Comments

Hi, this works ok except my csv has empty lines between rows
Hi, as suggested by @Justin Ezequiel, i need to specify newline=' '
I had the same initial question and vote this as the most complete answer thanks
can you please give an example where the keys are the first line of the CSV and the values are the proceeding lines.
3

You can't use DictWriter in that way, it is designed for key=column_header and value=[row_values].

You can instead iterate your dictionary and use csv.writerow

import csv


myDic = { "a" : 1, "b" : 2, "c" : 15}

header = ["word", "count"]

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    w = csv.writer(f)
    w.writerow(header)
    for k, v in myDic.items():
        w.writerow([k, v])

or as juanpa.arrivillaga pointed out you can writerows directly on the .items().

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    w.writerow(header)
    w.writerows(myDic.items())

However, storing your information for your csv in a dictionary in this way is very limiting since it can only ever be two columns so ensure that is an acceptable choice before continuing down this path.

8 Comments

Or just w.writerows(myDic.items())
That makes more sense. I wasn't thinking.
Hi, this works ok except my csv has empty lines between rows –
I can write a better response in the morning since I'm on mobile now but you may need to specify newline.
You're missing the initialization of your csv writer w = csv.writer(f) f.e.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.