Write Dictionary to CSV in Python

How to Write a Dictionary to a CSV File with One Line for Each ‘Key: Value’ Pair in Python?

I have a dictionary like this:

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

I want to write the data to a file dict.csv, with each key-value pair on its own line, like this:

key1: value_a
key2: value_b
key3: value_c

Here’s the code I tried:

import csv
f = open('dict.csv', 'wb')
w = csv.DictWriter(f, mydict.keys())
w.writerow(mydict)
f.close()

But this results in all the keys being written in one row and all the values in the next row.

Once I manage to write the dictionary like this, I also want to read it back into a new dictionary.

To explain further, the dictionary contains values and booleans from text controls 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 format (to make it easier for the user to edit the CSV file directly), and “Load Settings” should read from the file and update the text controls and checkboxes.

How can I Python write dictionary to csv in the format I need and read it back into a dictionary?

For a direct approach to meet your format, we use csv.writer to handle the writing of each key-value pair as a separate row.

Writing to CSV:

import csv

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

with open('dict.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    for key, value in mydict.items():
        writer.writerow([f'{key}: {value}'])

Reading from CSV:

mydict = {}
with open('dict.csv', 'r') as f:
    for line in f:
        key_value = line.strip().split(': ')
        mydict[key_value[0]] = key_value[1]

print(mydict)

Why this works:

  • csv.writer makes writing lines intuitive while maintaining consistency.
  • It’s easy to adapt for both writing and reading as it aligns with the key: value format.

Extra Tip:

If your dictionary values contain special characters like commas or colons, you may want to wrap the key-value strings in quotes to ensure proper handling when splitting lines.

If you’re open to alternatives, consider json for a structured, reliable way to store and retrieve dictionaries. While it doesn’t provide the exact “key: value per line” format, it’s a highly efficient option.

Writing to JSON:

import json

mydict = {'key1': 'value_a', 'key2': 'value_b', 'key3': 'value_c'}
with open('dict.json', 'w') as f:
    json.dump(mydict, f, indent=4)

Reading from JSON:

with open('dict.json', 'r') as f:
    mydict = json.load(f)

print(mydict)

Why consider JSON?

  • JSON ensures data integrity even if dictionary values are more complex (e.g., nested or containing special characters).
  • It’s easy to edit, load, and supports multiple programming languages.

For full control and adherence to your format, manual writing is straightforward and effective.

Writing to CSV:

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

with open('dict.csv', 'w') as f:
    for key, value in mydict.items():
        f.write(f'{key}: {value}\n')

Reading from CSV:

mydict = {}
with open('dict.csv', 'r') as f:
    for line in f:
        key_value = line.strip().split(': ')
        mydict[key_value[0]] = key_value[1]

print(mydict)

Advantages of this method:

  • Total control over the file format.
  • Can easily tweak formatting (e.g., change delimiters or spacing).

Further Optimization:

You can wrap the write/read logic in a function to reuse it for your “Save Settings” and “Load Settings” buttons in your wxPython app.