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
Run this program

Example 1: Python Pickling or Serializing

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

#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()

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

Example 2: Python Unpickling or Deserializing

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))

Output

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

Additional Reading

Like what you are reading!

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.

Leave a comment

Your email address will not be published. Required fields are marked*