Writing a dictionary in a csv file with one line for each "key: value"

I have a dictionary:

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

I want to write data to a dict.csv file 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 the keys on one line and all the values ​​on the next line.

When I manage to write such a file, I also want to read it in a new dictionary.

To explain my code, the dictionary contains values ​​and bools from textctrls and checkboxes (using wxpython). I want to add the Save Settings and Download Settings buttons. Save parameters should write the dictionary to the file in the specified way (so that the user can directly edit the csv file), load parameters should be read from the file and update text fields and flags.

+73
python dictionary csv
Dec 31 2018-11-11T00:
source share
8 answers

DictWriter does not work as 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 this:

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

which is pretty compact, but assumes you don't need to convert the type when reading

+153
Dec 31 '11 at 2:22
source share

The 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()] 
+12
Nov 02 '13 at 5:29
source share

Just to enable it, writing a dictionary to a CSV file can also be done with the Pandas package. In the above 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 consider is to set the 'orient' parameter to 'index' inside the from_dict method. This allows you to choose whether you want to write each dictionary key on a new line.

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

Your output will look like this:

 key1,a key2,b key3,c 

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

+12
Aug 03 '17 at 0:02
source share
 outfile = open( 'dict.txt', 'w' ) for key, value in sorted( mydict.items() ): outfile.write( str(key) + '\t' + str(value) + '\n' ) 
+4
Sep 25 '13 at 12:21
source share

Can you just do:

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

So you can have

key_1: value_1, key_2: value_2

+2
Dec 31 '11 at 2:13
source share

I personally always found the csv module annoying. I expect someone else to show you how to do this with this, but my quick and dirty solution:

 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 again, you will need to annoy the analysis a bit, especially if all this is on the same line. Here is an example of using the 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 
+1
Dec 31 '11 at 2:24
source share

I’m noob, I’m also late for these comments, haha, but you tried to add "s" to: w.writerow (mydict) like this: w.writerows (mydict), this problem happened to me, but from the lists, I used singular instead of plural. Pops! has been fixed.

0
Sep 14 '18 at 0:45
source share
 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

0
Jul 20 '19 at 9:46
source share



All Articles