Skip to Content

Save Python Dictionary to a Pickle File

Python objects can be saved (or serialized) as pickle files for later use. In this tutorial, we will look at how to save a Python dictionary as a pickle file with the help of some examples.

How to write Python dictionary to a pickle file?

Save python dictionary to pickle file

You can use the Python pickle module’s dump() function to serialize a dictionary to a pickle file. The following is the syntax –

import pickle

# save dictionary to pickle file
with open('my_filename.pickle', 'wb') as file:
    pickle.dump(my_dict, file, protocol=pickle.HIGHEST_PROTOCOL)

It saves the object as a pickle file which you can later use.

Exercise caution when working with pickle files. The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. See here.

Let’s look at some examples of using the above syntax –

For example, you have a dictionary storing the names to department mappings of employees in an office. You want to save this information in a pickle file so that it can be used later.

import pickle

# create a dictionary
employees = {
    "Jim": "Sales",
    "Dwight": "Sales",
    "Angela": "Accounting"
}
# save dictionary to pickle file
with open("employee_info.pickle", "wb") as file:
    pickle.dump(employees, file, pickle.HIGHEST_PROTOCOL)

The above code saves the dictionary employees to the file employee_info.pickle in our current working directory.

You can also deserialize a pickle file to get back your object using the pickle module. Use the pickle.load() function.

Let’s read the same dictionary from its pickle file that we saved above.

# laod a pickle file
with open("employee_info.pickle", "rb") as file:
    loaded_dict = pickle.load(file)

# display the dictionary
print(loaded_dict)

Output:

{'Jim': 'Sales', 'Dwight': 'Sales', 'Angela': 'Accounting'}

We get our original dictionary with all its content loaded from its pickle file.

You might also be interested in –

  1. Convert Python Dictionary to JSON
  2. Save Pandas DataFrame to a Pickle File


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.