Writing a dictionary to a csv file with one line for every ‘key: value’

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

Leave a Comment