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.
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:
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.
Can you just do:
So that you can have
key_1: value_1, key_2: value_2
I'm a noob, also late to this comments, haha, but, 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. Pops! was fix.
The
DictWriter
doesn't work the way you expect.To read it back:
which is quite compact, but it assumes you don't need to do any type conversion when reading
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'}
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:
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.