'Python write dictionary to csv with header

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.



Solution 1:[1]

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!

Solution 2:[2]

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

Solution 3:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Arnab Sarkar
Solution 3