How to Save a Python Dictionary as a JSON File?

As a developer working on a project for a US-based company, I recently encountered a situation where I needed to store a dictionary containing employee data in a JSON format for easy data exchange with other systems. In this tutorial, I will explain how to save a Python dictionary as a JSON file. In this article, I’ll walk you through the process step-by-step, providing detailed examples along the way.

Understand JSON and Python Dictionaries in Python

Before getting into the solution, let’s briefly discuss what JSON and Python dictionaries are:

  • JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It consists of key-value pairs and is commonly used for transmitting data between a server and a web application.
  • Python dictionaries are built-in data structures that store data as key-value pairs. They are mutable, unordered, and allow fast lookups using keys.

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

Convert Dictionary to JSON in Python

To convert a Python dictionary to JSON, we can use the json module in Python. The json module provides two methods for this purpose: json.dump() and json.dumps().

  • json.dump() is used to write the JSON representation of a Python object (e.g., a dictionary) to a file.
  • json.dumps() is used to convert a Python object to a JSON-formatted string.

Let’s consider an example where we have a dictionary containing employee data:

employee_data = {
    "name": "John Doe",
    "age": 35,
    "city": "New York",
    "country": "USA",
    "skills": ["Python", "Java", "C++"]
}

Check out How to Download Files from URLs Using Python?

1. Use json.dump()

To save the Python dictionary as a JSON file using json.dump(), follow these steps:

  1. Open a file in write mode using the open() function.
  2. Use json.dump() to write the Python dictionary to the file.
  3. Close the file.

Here’s an example:

import json

with open("employee.json", "w") as file:
    json.dump(employee_data, file)

In this code snippet, we open a file named “employee.json” in write mode using the with statement. We then use json.dump() to write the employee_data dictionary to the file. The resulting JSON file will look like this:

{"name": "John Doe", "age": 35, "city": "New York", "country": "USA", "skills": ["Python", "Java", "C++"]}

You can see the output in the screenshot below.

Save a Python Dictionary as JSON

Read How to Copy Files to Another Directory in Python?

2. Use json.dumps()

If you need to convert the Python dictionary to a JSON-formatted string instead of saving it directly to a file, you can use json.dumps(). Here’s an example:

import json

json_string = json.dumps(employee_data)
print(json_string)

The json.dumps() method converts the employee_data dictionary to a JSON-formatted string, which is then stored in the json_string variable. The output will be:

{"name": "John Doe", "age": 35, "city": "New York", "country": "USA", "skills": ["Python", "Java", "C++"]}

You can see the output in the screenshot below.

How to Save a Python Dictionary as JSON

You can also write this JSON string to a file using the write() method:

with open("employee.json", "w") as file:
    file.write(json_string)

Output:

{"name": "John Doe", "age": 35, "city": "New York", "country": "USA", "skills": ["Python", "Java", "C++"]}

You can see the output in the screenshot below.

Save a Python Dictionary as JSON write()

Check out How to Open a File in Python?

Best Practices and Tips

Here are some best practices and tips to keep in mind when working with JSON and Python dictionaries:

  1. Use meaningful and descriptive key names in your dictionaries to improve readability and maintainability.
  2. Ensure that the keys in your dictionary are strings, as JSON requires keys to be strings.
  3. If you have complex objects in your dictionary (e.g., custom class instances), you may need to define custom encoders or use the default parameter in json.dump() or json.dumps() to handle the serialization properly.
  4. When dealing with large datasets, consider using the indent parameter in json.dump() or json.dumps() to format the JSON output for better readability.
  5. Always close the file after writing to it to ensure that the data is properly saved and to free up system resources.

Read How to Check if a File Exists in Python?

Conclusion

In this tutorial, I explained how to save a Python dictionary as a JSON file. I discussed JSON and Python dictionaries, and how to convert a dictionary to JSON, I discussed two important methods such as json.dump() and json.dumps() and provided examples of how to use them. I also gave the best practices and tips.

You may 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.