How to Write a Dictionary to a File in Python?

In this tutorial, I will explain how to write a dictionary to a file in Python. As a developer working on a project for a U.S.-based client, I recently encountered a situation where I needed to save a dictionary containing user preferences to a file. After researching various methods, I discovered several effective ways to accomplish this task.

Write a Dictionary to a File in Python

Before we dive into writing dictionaries for files, let’s briefly review what dictionaries are in Python. A dictionary is a collection of key-value pairs, where each key is unique within the dictionary. We create a dictionary by placing key-value pairs inside curly brackets {}, separated by commas.

For example, let’s say we have a dictionary called user_preferences that stores preferences for a user named John from New York:

user_preferences = {
    "name": "John",
    "city": "New York",
    "favorite_color": "blue",
    "newsletter_subscribed": True
}

Read How to Write a Variable to a File in Python?

Method 1: Use JSON

One of the most common and convenient ways to write a Python dictionary to a file is by using the JSON (JavaScript Object Notation) format. JSON is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

Here’s how we can write our user_preferences dictionary to a file using JSON:

import json

# Write dictionary to JSON file
with open("user_preferences.json", "w") as file:
    json.dump(user_preferences, file)

I executed the above example code and added the screenshot below.

Write a Dictionary to a File in Python

In this example, we first import the json module. Then, we open a file named user_preferences.json in write mode using the with statement. Finally, we use the json.dump() function to write the dictionary to the file.

Check out How to Write a List to a File in Python?

Method 2: Use Pickle

Another way to write a dictionary to a file is by using the pickle module in Python. Pickle is used for serializing and deserializing objects, including Python dictionaries.

Here’s an example of how to write our dictionary to a file using pickle:

import pickle

# Write dictionary to binary file
with open("user_preferences.pkl", "wb") as file:
    pickle.dump(user_preferences, file)

I executed the above example code and added the screenshot below.

How to Write a Dictionary to a File in Python

In this case, we import the pickle module and open a file named user_preferences.pkl in write binary mode ("wb"). We then use the pickle.dump() function to write the dictionary to the file.

Read How to Download and Extract ZIP Files from a URL Using Python?

Method 3: Use CSV

If you prefer to save the dictionary as a CSV (Comma-Separated Values) file, you can use the csv module in Python.

Here’s an example:

import csv

# Write dictionary to CSV file
with open("user_preferences.csv", "w") as file:
    writer = csv.writer(file)
    for key, value in user_preferences.items():
        writer.writerow([key, value])

I executed the above example code and added the screenshot below.

Write a Dictionary to a File in Python csv file

In this approach, we import the csv module and open a file named user_preferences.csv in write mode. We create a CSV writer object using csv.writer() and then iterate over the dictionary items using the items() method. For each key-value pair, we write a row to the CSV file using the writerow() method.

Check out Python Create File

Conclusion

In this tutorial, I explained how to write a dictionary to a file in Python. I discussed mainly three methods to accomplish tasks, such as using the JSON module, Pickle module, and the CSV module.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.