Python Pickle – Serialize and De-serialize Objects

Python Pickle

Python Pickle module is used to serialize and de-serialize Python Objects. Serialization is used to convert Python Object to a single stream of characters and write the stream to a file storage. De-serialization is used to construct a Python Object from the data read from file storage(which is serialized previously).

Among the Python community, Pickle is referred in terms of verb, adjective, noun, etc., like Pickling, Picklable, Pickled, Unpickle, etc. In a day or two, you will get used to this terminology, if you are working with Python Pickle and referring multiple online resources.

Which Datatypes can be Pickled?

Following Python Datatypes can be pickled.

  • Booleans – True, False
  • Integers – 25, 6, 896
  • Floats – 2.56, 8.124, 2.14
  • Complex Numbers – 3+4j, 9-j, 7j
  • Strings – (Normal, Unicode)
  • Tuples
  • Lists
  • Sets
  • Dictionaries
  • Top level Functions and Class Objects of a Module

Which datatypes cannot be Pickled?

Though most of the datatypes and objects can be Pickled, some cannot be. Those are:

  • Generators
  • Inner classes
  • Lambda Functions
  • Defaultdicts

Import Pickle Module

To import Pickle module into your program, use the following code.

import pickle

Examples

1. Pickle a dictionary and write to a file

In the following example, we will take a dictionary and pickle it. After pickling, the serialized data is written to a file. We just need to specify the file name. There will be no extension to the pickle file.

Python Program

import pickle

# Take a dictionary
marks = { 'Alex': 87, 'Lini': 92, 'Kiku': 90 }

# Create a pickle file
picklefile = open('marks', 'wb')

# Pickle the dictionary and write it to file
pickle.dump(marks, picklefile)

# Close the file
picklefile.close()
Copy

You would see that a file named marks is created at the current working directory.

2. Un-pickle or deserialise data

In the following example, we will unpickle the file generated in the above example.

Python Program

import pickle

# Create a pickle file
picklefile = open('marks', 'rb')

# Pickle the dictionary and write it to file
marks = pickle.load(picklefile)

# Close the file
picklefile.close()

# Print the dictionary
print(marks)
print(type(marks))
Copy

Output

{'Alex': 87, 'Lini': 92, 'Kiku': 90}
<class 'dict'>

Additional Reading

Like what you are reading! Check out our other tutorials covering pickle.

Summary

In this tutorial of Python Examples, we learned how to use Pickle library to serialize or de-serialize Python objects, with the help of example programs.

Related Tutorials

Code copied to clipboard successfully 👍