06-15-2022, 03:15 AM
How to Save a Dictionary to a File in Python
Rate this post
Summary: You can use Python’s library to save dictionary data to a file. Another efficient approach to save dictionary data to a file is to use Python’s built-in package. You can also use simple file handling functions to store dictionary data in a text file directly.
Problem: Given a Python dictionary. How will you save the data from the dictionary to a file so that it can be loaded to be used later?
You might need the help of persistent storage systems like databases or files to store serialized data structures like arrays, lists, and dictionaries. One of the major reasons behind doing so is databases and files are reusable, i.e., after analyzing the given data, we can store it in the file, and later that data can be read to use in an application.
This article will deal with dictionary data that you can store in a file.
Example: Consider the following dictionary:
Challenge: How will you store the key-value pairs of the above dictionary in a file?
Related Tutorials:
There are numerous ways to store dictionary data in a file using Python. Let’s have a look at some of them:
[b]Method 1: Using Pickle[/b]
Approach:
Code: Let’s visualize the above approach with the help of the following code snippet:
Output:
![[Image: image-82.png]](https://blog.finxter.com/wp-content/uploads/2022/06/image-82.png)
Output Console:
[b]Method 2: Using json[/b]
Approach:
Code:
Output:
![[Image: image-83.png]](https://blog.finxter.com/wp-content/uploads/2022/06/image-83.png)
Output Console:
Note: The method is used to convert a Python object to a JSON string.
[b]Method 3: Using Numpy[/b]
Using JSON and Pickle are the best options when it comes to storing a dictionary to a file. But we also have another way of doing so using the Numpy module.
Approach: Call the function to save the file into the disk. To read the data from this file us call the function.
Code:
Read Here: NumPy Tutorial – Everything You Need to Know to Get Started
Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)
![[Image: Cover_Coffee_Break_NumPy-200x300.jpg]](https://blog.finxter.com/wp-content/uploads/2019/04/Cover_Coffee_Break_NumPy-200x300.jpg)
Method 4: Basic Approach
Last but not the least, you can store the dictionary data to a simple text file by simply writing the data to the file using file handling functions.
Approach:
Output:
![[Image: image-84.png]](https://blog.finxter.com/wp-content/uploads/2022/06/image-84.png)
Recommended Reads on File Handling:
Conclusion
We learned four ways of storing the dictionary data to a file in Python in this article. The most suitable ways of storing the dictionary data in a file are using the JSON or the pickle modules. However, feel free to try out the other ways discussed in this tutorial.
I hope this article helped you. Please subscribe and stay tuned for more interesting tutorials and discussions.
But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners
Rate this post
Summary: You can use Python’s
Code:
pickleCode:
JSONProblem: Given a Python dictionary. How will you save the data from the dictionary to a file so that it can be loaded to be used later?
You might need the help of persistent storage systems like databases or files to store serialized data structures like arrays, lists, and dictionaries. One of the major reasons behind doing so is databases and files are reusable, i.e., after analyzing the given data, we can store it in the file, and later that data can be read to use in an application.
This article will deal with dictionary data that you can store in a file.
Example: Consider the following dictionary:
Code:
d = {'country': 'Germany', 'capital': 'Berlin'}Challenge: How will you store the key-value pairs of the above dictionary in a file?
Related Tutorials:
- Writing a List to a File in Python
- How to Read a Dictionary from a File
- Correct Way to Write line To File in Python
There are numerous ways to store dictionary data in a file using Python. Let’s have a look at some of them:
[b]Method 1: Using Pickle[/b]
- Pickle is a module in Python that uses binary protocols to serialize and de-serialize an object structure. “Pickling” refers to the process of converting a Python object to a byte stream. “Unpickling” is just the reverse operation wherein a byte stream is converted to a Python object. Pickling is also sometimes referred to as serialization.
- A good idea to implement a Pickle file is when you are dealing with sensitive data or when you need to keep a program status across sessions.
Approach:
- Create the pickle file (i.e., filename.pkl) with the help of the function. Since we will be storing the data in a pickle file which stores the data as a binary stream, hence, open the file in binary (“Code:
open(filename, mode)“) mode.Code:wb
- Use the method to store/serialize the dictionary data to the file.Code:
pickle.dump(dictionary, filename)
- To read data from this file, call the method.Code:
pickle.load(filename)
- Note: Remember to close the file.
Code: Let’s visualize the above approach with the help of the following code snippet:
Code:
import pickle
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.pkl", "wb")
pickle.dump(d, file)
file.close()
file = open("dictionary_data.pkl", "rb")
output = pickle.load(file)
print(output)
file.close()Output:
![[Image: image-82.png]](https://blog.finxter.com/wp-content/uploads/2022/06/image-82.png)
Output Console:
Code:
{'country': 'Germany', 'capital': 'Berlin'}Approach:
- Open the file in write mode by calling .Code:
open('filename','mode')
- Use the function to convert the dictionary data to the json format and write it to the file.Code:
json.dump(dictionary, filename)
- To read the data from this file, read the data from it by calling the function.Code:
file.read()
- Note: Remember to close the file.
Code:
Code:
import json
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.json", "w")
json.dump(d, file)
file.close()
file = open("dictionary_data.json", "r")
output = file.read()
print(output)
file.close()Output:
![[Image: image-83.png]](https://blog.finxter.com/wp-content/uploads/2022/06/image-83.png)
Output Console:
Code:
{"country": "Germany", "capital": "Berlin"}Note: The
Code:
json.dump()[b]Method 3: Using Numpy[/b]
Using JSON and Pickle are the best options when it comes to storing a dictionary to a file. But we also have another way of doing so using the Numpy module.
Approach: Call the
Code:
np.save(filename, dictionary)Code:
np.load('file.npy', allow_pickle='TRUE').item()Code:
Code:
import numpy as np
d = {'country': 'Germany', 'capital': 'Berlin'}
np.save('file.npy', d)
read_d = np.load('file.npy', allow_pickle='TRUE').item()
print(read_d)Read Here: NumPy Tutorial – Everything You Need to Know to Get Started
Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)
![[Image: Cover_Coffee_Break_NumPy-200x300.jpg]](https://blog.finxter.com/wp-content/uploads/2019/04/Cover_Coffee_Break_NumPy-200x300.jpg)
Method 4: Basic Approach
Last but not the least, you can store the dictionary data to a simple text file by simply writing the data to the file using file handling functions.
Approach:
- Call the function to create/open the file in the write mode.Code:
open('filename.txt', 'w')
- Use the function to write the dictionary data to the file and then close the file.Code:
file.write(str(dictionary))
- To read the data from this file open up the file and use the method to read the data from this file.Code:
file.read()
Code:
d = {'country': 'Germany', 'capital': 'Berlin'}
f = open('file.txt', 'w')
f.write(str(d))
f.close()
f = open('file.txt', 'r')
data = f.read()
print(data)
f.close()Output:
![[Image: image-84.png]](https://blog.finxter.com/wp-content/uploads/2022/06/image-84.png)
Recommended Reads on File Handling:
Conclusion
We learned four ways of storing the dictionary data to a file in Python in this article. The most suitable ways of storing the dictionary data in a file are using the JSON or the pickle modules. However, feel free to try out the other ways discussed in this tutorial.
I hope this article helped you. Please subscribe and stay tuned for more interesting tutorials and discussions.
But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners

