How to Pickle a Python Dict and Load It Back

Save a dictionary to a binary file with pickle.dump() and reload it with pickle.load(), showing the round trip and type preservation.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 16 views 0 copies

Python code

17 lines
Python 3.9+
import pickle

data = {"name": "Alice", "scores": [87, 92, 95], "active": True}

print("Original dict:", data)

with open("safe_demo.pkl", "wb") as f:
    pickle.dump(data, f)

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

print("Loaded dict:", loaded)
print("Type:", type(loaded).__name__)
print("Equal to original:", loaded == data)

print("Safety warning: Only unpickle data from trusted sources — pickle is not secure.")

Output

stdout
Original dict: {'name': 'Alice', 'scores': [87, 92, 95], 'active': True}
Loaded dict: {'name': 'Alice', 'scores': [87, 92, 95], 'active': True}
Type: dict
Equal to original: True
Safety warning: Only unpickle data from trusted sources — pickle is not secure.

How it works

pickle.dump serializes the dict to a binary file, preserving the exact types and structure. pickle.load reads that file and reconstructs a new dict in memory. The comparison loaded == data returns True because the dicts contain identical key-value pairs and types. Always treat pickle files as executable code; they can execute arbitrary code during unpickling, so only load from sources you control.

Common mistakes

  • Unpickling data from untrusted sources, which can execute arbitrary code
  • Forgetting to use 'rb'/'wb' modes instead of text modes for pickle files
  • Expecting pickle to preserve the original object identity; it creates a new object

Variations

  1. Use `pickle.loads` and `pickle.dumps` to work with bytes in memory instead of files
  2. Use `json.dump` and `json.load` when you need human-readable or interoperable serialization

Real-world use cases

  • Caching expensive computations or large data structures between program runs.
  • Saving ML model artifacts or trained tokenizers to disk for later reload.
  • Persisting session or application state in a custom binary format.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.