How to Save a Dictionary to a File in Python

5/5 - (1 vote)

Summary: You can use Python’s pickle 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 JSON 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:

d = {'country': 'Germany',
     'capital': 'Berlin'}

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:

Method 1: Using Pickle

  • 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 open(filename, mode) 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 (“wb“) mode.
  • Use the pickle.dump(dictionary, filename) method to store/serialize the dictionary data to the file.
  • To read data from this file, call the pickle.load(filename) method.
  • Note: Remember to close the file.

Code: Let’s visualize the above approach with the help of the following code snippet:

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:

Output Console:

{'country': 'Germany', 'capital': 'Berlin'}

Method 2: Using json

Approach:

  • Open the file in write mode by calling open('filename','mode').
  • Use the json.dump(dictionary, filename) function to convert the dictionary data to the json format and write it to the file.
  • To read the data from this file, read the data from it by calling the file.read() function.
  • Note: Remember to close the file.

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:

Output Console:

{"country": "Germany", "capital": "Berlin"}

Note: The json.dump() method is used to convert a Python object to a JSON string.

Method 3: Using Numpy

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 np.save(filename, dictionary) function to save the file into the disk. To read the data from this file us call the np.load('file.npy', allow_pickle='TRUE').item() function.

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.)

Coffee Break NumPy

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 open('filename.txt', 'w') function to create/open the file in the write mode.
  • Use the file.write(str(dictionary)) function to write the dictionary data to the file and then close the file.
  • To read the data from this file open up the file and use the file.read() method to read the data from this file.
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:

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.


Check out 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!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners