Write a dictionary to a file in Python
Last Updated : 01 Apr, 2025
A dictionary store data using key-value pairs. Our task is that we need to save a dictionary to a file so that we can use it later, even after the program is closed. However, a dictionary cannot be directly written to a file. It must first be changed into a format that a file can store and read later. Let’s explore different methods to achieve this.
Using json.dump()
json.dump() function directly writes the dictionary as a JSON object into a file making it easy to read and retrieve later. Since JSON is a text-based format, it can be opened easily and is better for readability purposes.
Python import json d = {'Name': "Bob",'Age': 28 } # writing dictionary to a file as JSON with open('data.json', 'w') as f: json.dump(d, f)
Output:

data.json file
Explanation: After defining the dictionary, a file named ‘data.json’ is opened in write mode (‘w’), allowing data to be stored in it. Finally, the json.dump(d, f) function is used to directly write the dictionary into the file in JSON format, ensuring that the data is structured and can be easily retrieved later.
Using json.dumps()
json.dumps() function converts a dictionary into a JSON-formatted string, which can then be written to a file manually using write(). This allows adding formatting options like indentation for better readability.
Python import json d = {'Name': "Bob", 'Age': 28} # Convert dictionary to a JSON string and write to file with open('data.json', 'w') as file: file.write(json.dumps(d, indent=4))
Output:

data.json file
Explanation: json.dumps(d, indent=4) function is used to convert it into a JSON-formatted string with indentation for better readability. Finally, the write() method is used to store this formatted JSON string in the file, ensuring that the data remains structured and easy to read when accessed later.
Using pickle.dump()
pickle module allows saving a dictionary in binary format, preserving its exact structure. The dump() function serializes the dictionary and writes it to a binary file, which can later be retrieved using load().
Python from types import resolve_bases import pickle d = {'Name': "bob", 'Age': 28} # writing dictionary to a binary file with open('data.pkl', 'wb') as file: pickle.dump(d, file) # Reading dictionary from the binary file with open('data.pkl', 'rb') as file: res = pickle.load(file) print(res)
Output:

data.pkl file
{'Name': 'bob', 'Age': 28}
Explanation: pickle.dump(d, file) function serializes the dictionary and writes it to the file, preserving its structure. Later, the same file is opened in binary read mode (‘rb’), and the pickle.load(file) function is used to deserialize the stored data, converting it back into a dictionary.
Using str()
The simplest way to store a dictionary in a file is by converting it into a string using str(), then writing it using write(). This method, however, does not provide a structured format and requires additional processing when reading the data back.
Python d = {'Name': "Bob", 'Age': 28} # Convert dictionary to string and write to file with open('data.txt', 'w') as file: file.write(str(d))
Output:

data.txt file
Explanation: str(d) function is used to convert the dictionary into a string format, which is then written to the file using the write() method.
Similar Reads
Python - Write dictionary of list to CSV
In this article, we will discuss the practical implementation of how to write a dictionary of lists to CSV. We can use the csv module for this. The csvwriter file object supports three methods such as csvwriter.writerow(), csvwriter.writerows(), csvwriter.writeheader(). Syntax: csv.writer(csvfile,
4 min read
How to save a Python Dictionary to a CSV File?
CSV (Comma-Separated Values) files are a popular format for storing tabular data in a simple, text-based format. They are widely used for data exchange between applications such as Microsoft Excel, Google Sheets and databases. In this article, we will explore different ways to save a Python dictiona
4 min read
How to Create a Dictionary in Python
The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Add new keys to a dictionary in Python
In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
2 min read
How to implement Dictionary with Python3?
This program uses python's container called dictionary (in dictionary a key is associated with some information). This program will take a word as input and returns the meaning of that word. Python3 should be installed in your system. If it not installed, install it from this link. Always try to ins
3 min read
Dictionary with Tuple as Key in Python
Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
4 min read
Turning a Dictionary into XML in Python
XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elemen
3 min read
Ways to create a dictionary of Lists - Python
A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key. Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
How to Add Function in Python Dictionary
Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
5 min read
How to Alphabetize a Dictionary in Python
Alphabetizing a dictionary in Python can be useful for various applications, such as data organization and reporting. In this article, we will explore different methods to alphabetize a dictionary by its keys or values. Dictionary OrderingIn Python, dictionaries are a powerful data structure that al
3 min read