» Quick Introduction to Python » 4. Common Modules » 4.5 pickle

pickle

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation.

Pickle a dictionary into file

import pickle

user_data = {'first': 'Jack', 'last': 'Smith', 'age': 50}
f = open('user.dat', 'wb')
pickle.dump(user_data, f) # pickle into the file
f.close()

Unpickle from file

import pickle

f = open('user.dat', 'rb')
user_data = pickle.load(f)
f.close()

print(user_data) # {'first': 'Jack', 'last': 'Smith', 'age': 50}

Code Challenge

Try to modify the code in the editor to make it output the answer.

Loading...
> code result goes here
Prev
Next