Junior
What is the difference between pickle.dumps and pickle.dump, as well as pickle.loads and pickle.load?
sobes.tech AI
Answer from AI
pickle.dumps() serializes an object into a byte string, while pickle.dump() serializes an object into a file object (stream). Correspondingly, pickle.loads() deserializes a byte string back into an object, and pickle.load() deserializes an object from a file object (stream).
Examples:
import pickle
data = {'a': 1, 'b': 2}
# dumps: serialization into a byte string
pickled_string = pickle.dumps(data)
# b'\x80\x04\x95\x11\x00\x00\x00\x00\x00\x00\x00}\x94(X\x01\x00\x00\x00a\x94K\x01X\x01\x00\x00\x00b\x94K\x02u.'
# loads: deserialization from a byte string
unpickled_data_from_string = pickle.loads(pickled_string)
# {'a': 1, 'b': 2}
# dump: serialization into a file object
with open('data.pkl', 'wb') as f:
pickle.dump(data, f) # writes bytes to the file data.pkl
# load: deserialization from a file object
with open('data.pkl', 'rb') as f:
unpickled_data_from_file = pickle.load(f)
# {'a': 1, 'b': 2}
Summarizing:
| Function | Input | Output | Purpose |
|---|---|---|---|
pickle.dumps |
Object | Bytes | Convert object to bytes |
pickle.loads |
Bytes | Object | Reconstruct object from bytes |
pickle.dump |
Object, file | None | Write object to a file |
pickle.load |
File | Object | Read object from a file |