Pickle examples

Python pickle module

In this example we want to use the Python pickle module to save the following dict in pickle format:

pyviz = {
    "Title": "PyViz Tutorial",
    "Language": "de",
    "Authors": "Veit Schiele",
    "License": "BSD-3-Clause",
    "Publication date": "2020-04-13",
import pickle
with open("pyviz.pkl", "wb") as f:
    pickle.dump(pyviz, f, pickle.HIGHEST_PROTOCOL)

Now we read the pickle file again:

with open("pyviz.pkl", "rb") as f:
    pyviz = pickle.load(f)

{'Title': 'PyViz Tutorial', 'Language': 'de', 'Authors': 'Veit Schiele', 'License': 'BSD-3-Clause', 'Publication date': '2020-04-13'}

This way we can easily store Python objects persistently.


pickle can only be recommended as a short-term storage format. The problem is that the format is not guaranteed to remain stable over time; an object picked today may not be unpickled with a later version of the library.


All pandas objects have a to_pickle method that writes data to disk in pickle format:

import pandas as pd

books = pd.read_pickle("books.pkl")

id title language author license date
0 1 Python basics en Veit Schiele BSD-3-Clause 2021-10-28
1 2 Jupyter Tutorial en Veit Schiele BSD-3-Clause 2019-06-27
2 3 Jupyter Tutorial de Veit Schiele BSD-3-Clause 2020-10-26
3 4 PyViz Tutorial en Veit Schiele BSD-3-Clause 2020-04-13

pandas objects all have a to_pickle method that writes the data to the hard disk in pickle format: