Explain Codes LogoExplain Codes Logo

Storing Python dictionaries

python
serialization
deserialization
data-structures
Alex KataevbyAlex Kataev·Mar 7, 2025
TLDR

Instantly store a Python dict using json for persistence:

import json # Save a dict with open('my_dict.json', 'w') as file: json.dump({'key': 'value'}, file) # Like hiding the key 🗝️ under the digital doormat! # Load it back with open('my_dict.json', 'r') as file: data = json.load(file) # And the treasure is found!

Here json.dump() stores data, and json.load() retrieves it in a .json format, intelligible by all programming languages.

Quick and dirty with Pickle

Don't mind about cross-language readability or security? pickle is your friend:

import pickle # Save your dict with open('my_dict.pkl', 'wb') as file: pickle.dump({'key': 'value'}, file) # Pickling! Because cucumbers are too mainstream... # Reload it with open('my_dict.pkl', 'rb') as file: data = pickle.load(file) # Be careful while opening the jar!

Note: Use 'wb' and 'rb' modes for binary writings and readings respectively with pickle.

Pretty JSON for Homo-sapiens

When readability is important, you can make JSON pretty:

# Save your dict - now pretty! with open('my_dict.json', 'w') as file: json.dump({'key': 'value'}, file, indent=4, sort_keys=True) # Because pretty matters!

Considering alternatives: ujson and klepto

For ultra-fast operations, swap json with ujson:

import ujson # Save your dict - now with ujson! with open('my_dict.json', 'w') as file: ujson.dump({'key': 'value'}, file) # Super-speed, because we are always in a hurry!

For dictionary-like archiving to a file, directory, or database, check klepto:

from klepto.archives import file_archive # Save your dict - now with klepto! my_dict = {'key': 'value'} archive = file_archive('my_dict.klepto') archive['my_dict'] = my_dict archive.dump() # Ultimate thief or really-advanced archivist? You decide!

Hashes to ashes, bits to bytes

When files are too large or complex, consider other serialization/deserialization methods:

  • dill: stores almost anything in Python, perfect for complex objects.
  • ujson: ultra-fast encoding and decoding, when time is money.
  • klepto: dictionary-like archiving to files, directories, or databases, when order and structure are your thing.

Remember: Good encoding and decoding practices can save you from many headaches.