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

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.

This question is related to python csv dictionary

The answer is


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

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

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.


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.


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


#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

import csv

dict = {"Key Header":"Value Header", "key1":"value1", "key2":"value2"}

with open("test.csv", "w") as f:
    writer = csv.writer(f)
    for i in dict:
      writer.writerow([i, dict[i]])
f.close() 

enter image description here


outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
    outfile.write( str(key) + '\t' + str(value) + '\n' )

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to csv

Pandas: ValueError: cannot convert float NaN to integer Export result set on Dbeaver to CSV Convert txt to csv python script How to import an Excel file into SQL Server? "CSV file does not exist" for a filename with embedded quotes Save Dataframe to csv directly to s3 Python Data-frame Object has no Attribute (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape How to write to a CSV line by line? How to check encoding of a CSV file

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python