Writing a dictionary to a csv file with one line for every 'key: value'
Solution 1:
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
Solution 2:
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.
Solution 3:
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()]
Solution 4:
outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
outfile.write( str(key) + '\t' + str(value) + '\n' )