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.
Python code
17 linesimport 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
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
- Use `pickle.loads` and `pickle.dumps` to work with bytes in memory instead of files
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.