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?

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 –
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
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 –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.