Windy71
Windy71

Reputation: 909

How to get Dictwriter to write a key value pair to each line of a csv

I have some code which works in solar as it writes a dict to a csv file. It writes the keys as a line of headers and the corresponding values in a line underneath. What I would like to do is have each key value pair from the dict be written to a single line, then the next key, value pair be written on a newline. Is this possible with Dictwriter?

Code

import csv

def write_csv(fullfilepath, mydict):
    """ Write a simple dict to a csv file at given filename and path """
    with open(fullfilepath, 'w', newline='') as filey:
        w = csv.DictWriter(filey, mydict.keys())
        print(type(w))
        w.writeheader()
        w.writerow(mydict)

fullfilepath = r"C:\path\to\Desktop\csv\file\dummy.csv"
mydict = {"a":1, "b":2, "c":3}
write_csv(fullfilepath, mydict)

Upvotes: 0

Views: 570

Answers (2)

Windy71
Windy71

Reputation: 909

I found out how it can be done. This will write a csv file which has the key value pairs on a single line, the newline ='' makes sure there is no empty line separating each row in the csv.

def write_csv(fullfilepath, mydict):
    """ Write a simple dict to a csv file at given filename and path """
    with open(fullfilepath, 'w', newline = '') as csv_file:  
        writer = csv.writer(csv_file)
        for key, value in mydict.items():
            writer.writerow([key, value])

Upvotes: 0

Amit Nanaware
Amit Nanaware

Reputation: 3356

try file opening with append mode like this:

with open(fullfilepath, 'a', newline='') as filey:

It will not write keys and values on same row. The keys and values will be on different rows only

If you want to write on same line you can prepare string , seperated like this:

keyrow = ",".join(mydict.keys())
valuerow = ",".join(mydict.values())
row = keyrow + ',' + valuerow

Upvotes: 1

Related Questions