Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 800
user1106770 Avatar asked Dec 31 '11 02:12

user1106770


People also ask

How do I write a dictionary in a CSV file?

Easiest way is to open a csv file in 'w' mode with the help of open() function and write key value pair in comma separated form. The csv module contains DictWriter method that requires name of csv file to write and a list object containing field names.

How do you create a dictionary with one key and multiple values?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.


3 Answers

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

like image 145
Ricardo Cárdenes Avatar answered Sep 28 '22 19:09

Ricardo Cárdenes


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.

like image 31
Ivan Calderon Avatar answered Sep 28 '22 19:09

Ivan Calderon


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()]
like image 24
Phil Horowitz Avatar answered Sep 28 '22 20:09

Phil Horowitz