Writing a dictionary to a csv file with one line for every 'key: value'

Question:

I’ve got a dictionary:

mydict = {key1: value_a, key2: value_b, key3: value_c}

I want to write the data to a file dict.csv, in this style:

key1: value_a
key2: value_b
key3: value_c

I wrote:

import csv
f = open('dict.csv','wb')
w = csv.DictWriter(f,mydict.keys())
w.writerow(mydict)
f.close()

But now I have all keys in one row and all values in the next row..

When I manage to write a file like this, I also want to read it back to a new dictionary.

Just to explain my code, the dictionary contains values and bools from textctrls and checkboxes (using wxpython). I want to add “Save settings” and “Load settings” buttons.
Save settings should write the dictionary to the file in the mentioned way (to make it easier for the user to edit the csv file directly), load settings should read from the file and update the textctrls and checkboxes.

Asked By: user1106770

||

Answers:

Can you just do:

for key in mydict.keys():
    f.write(str(key) + ":" + str(mydict[key]) + ",");

So that you can have

key_1: value_1, key_2: value_2

Answered By: louis.luo

The DictWriter doesn’t work the way you expect.

with open('dict.csv', 'w') as csv_file:  
    writer = csv.writer(csv_file)
    for key, value in mydict.items():
       writer.writerow([key, value])

To read it back:

with open('dict.csv') as csv_file:
    reader = csv.reader(csv_file)
    mydict = dict(reader)

which is quite compact, but it assumes you don’t need to do any type conversion when reading

Answered By: Ricardo Cárdenes

I’ve personally always found the csv module kind of annoying. I expect someone else will show you how to do this slickly with it, but my quick and dirty solution is:

with open('dict.csv', 'w') as f:  # This creates the file object for the context 
                                  # below it and closes the file automatically
    l = []
    for k, v in mydict.iteritems(): # Iterate over items returning key, value tuples
        l.append('%s: %s' % (str(k), str(v))) # Build a nice list of strings
    f.write(', '.join(l))                     # Join that list of strings and write out

However, if you want to read it back in, you’ll need to do some irritating parsing, especially if it’s all on one line. Here’s an example using your proposed file format.

with open('dict.csv', 'r') as f: # Again temporary file for reading
    d = {}
    l = f.read().split(',')      # Split using commas
    for i in l:
        values = i.split(': ')   # Split using ': '
        d[values[0]] = values[1] # Any type conversion will need to happen here
Answered By: Griffith Rees
outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
    outfile.write( str(key) + 't' + str(value) + 'n' )
Answered By: FCAlive

Easiest way is to ignore the csv module and format it yourself.

with open('my_file.csv', 'w') as f:
    [f.write('{0},{1}n'.format(key, value)) for key, value in my_dict.items()]
Answered By: Phil Horowitz

Just to give an option, writing a dictionary to csv file could also be done with the pandas package. With the given example it could be something like this:

mydict = {'key1': 'a', 'key2': 'b', 'key3': 'c'}

import pandas as pd

(pd.DataFrame.from_dict(data=mydict, orient='index')
   .to_csv('dict_file.csv', header=False))

The main thing to take into account is to set the ‘orient’ parameter to ‘index’ inside the from_dict method. This lets you choose if you want to write each dictionary key in a new row.

Additionaly, inside the to_csv method the header parameter is set to False just to have only the dictionary elements without annoying rows. You can always set column and index names inside the
to_csv method.

Your output would look like this:

key1,a
key2,b
key3,c

If instead you want the keys to be the column’s names, just use the default ‘orient’ parameter that is ‘columns’, as you could check in the documentation links.

Considering the comment from @Rabarberski, when using orient='columns you should configure data as follows:

d = {k: [v] for k, v in mydict.items()}

Answered By: Ivan Calderon

Have you tried to add the "s" on: w.writerow(mydict) like this: w.writerows(mydict)? This issue happened to me but with lists, I was using singular instead of plural.

Answered By: Hikhuj
#code to insert and read dictionary element from csv file
import csv
n=input("Enter I to insert or S to read : ")
if n=="I":
    m=int(input("Enter the number of data you want to insert: "))
    mydict={}
    list=[]
    for i in range(m):
        keys=int(input("Enter id :"))
        list.append(keys)
        values=input("Enter Name :")
        mydict[keys]=values

    with open('File1.csv',"w") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=list)
        writer.writeheader()
        writer.writerow(mydict)
        print("Data Inserted")
else:
    keys=input("Enter Id to Search :")
    Id=str(keys)
    with open('File1.csv',"r") as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row[Id]) #print(row) to display all data
Answered By: Ashish Nandan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.