pickle converts almost any Python object (lists, dictionaries, sets, tuples, instances of your classes…) into bytes and rebuilds it later. It is the fastest way to save a program's state between runs.
import pickle
data = {"list": [1, 2, (3, 4)], "set": {5, 6}, "text": "hello"}
binary = pickle.dumps(data) # object -> bytes
print(type(binary).__name__) # bytes
copy = pickle.loads(binary) # bytes -> object
print(copy == data, copy is data) # True False
print(copy["list"][2]) # (3, 4) keeps the tuples
with open("data.pkl", "wb") as f: # to a file, always in binary mode
pickle.dump(data, f)
with open("data.pkl", "rb") as f:
print(pickle.load(f)["set"]) # {5, 6}
# json does not keep everything: tuples become lists and sets cannot be saved
import json
print(json.loads(json.dumps({"t": (3, 4)}))) # {'t': [3, 4]}
dumps/loadswork withbytes;dump/loadwith files opened in binary mode ("wb"and"rb").- It keeps the types: tuples, sets and your own objects come back as they were, something JSON does not do.
- Only Python reads it, and the result may change between language versions: it is not an exchange or long-term archive format.
- Security: loading a pickle runs code that comes inside it. Never
pickle.loada file or network data that you did not create yourself. For external data, use JSON.
You practice it in Copy data with pickle.