- Python Pickle – Serialize and De-serialize Objects
- Which Datatypes can be Pickled?
- Which datatypes cannot be Pickled?
- Import Pickle Module
- Examples
- 1. Pickle a dictionary and write to a file
- 2. Un-pickle or deserialise data
- Additional Reading
- Summary
- Python Pickle Tutorial
- Python Pickling Examples
- Example 1: Pickle a list
- Example 2: Pickle a dictionary
- Example 3: Pickle a tuple
- Python Unpickling Examples
- Example 1: Unpickle a list
- Example 2: Unpickle a dictionary
- Example 3: Unpickle a tupleOutput
- Conclusion
- About the author
- Kamran Sattar Awaisi
Python Pickle – Serialize and De-serialize Objects
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:
Import Pickle Module
To import Pickle module into your program, use the following code.
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()
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))
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.
Python Pickle Tutorial
Python developers want to save the data objects like lists, dictionaries, tuples, and classes into a file. In this situation, the Python pickle module comes into play.
Pickle is the Python built-in module that is used for serializing and deserializing the Python object’s structure. Serialization is the process of converting the Python object into a byte stream (0 and 1). It is also known as pickling. The purpose of the pickling process is to save the Python object on a disk in the form of a byte stream. The Python pickled object can be converted back into the Python object, and this process is known as unpickling or deserialization.
The Python pickling is useful when we have to save the state of the Python object and perform the data analysis task. For example, when we are working with deep learning algorithms, and we want to use it for a later time. In this condition, we can store it on the disk for later usage. However, pickling is not a good option when we are working with various programming languages. The pickled object cannot be unpickled in any other programming language, as it does not have cross-language support. The object that is pickled in Python, may only be unpickled in Python too. The same is applicable for different Python versions; an object that is pickled in a specific Python version, may not be unpickled properly in another version. To perform the pickling and unpickling process, first, we need to import the pickle module in our Python script.
In this article, we will learn to use the Python pickle module for performing pickling and unpickling with examples.
Python Pickling Examples
Let’s see some examples to understand the Python pickling process. Before performing the pickling operation, we need to open the file in writing mode. The file must be opened in the binary mode, as the pickled object is stored in the byte stream. The dump() is a function of the pickle module that is used to create the pickle. It takes two arguments, i.e., the Python object to be pickled and the file where the pickled object will be saved.
Example 1: Pickle a list
In the given example, we have created a list of numbers and pickled it using the pickle.dump() function.
num_list = [ 1 , 2 , 3 , 4 , 5 , 6 ]
#pickling the list and storing in a file
listfile = open ( ‘listPickle’ , ‘wb’ )
pickle . dump ( num_list , listfile )
print ( «The list pickle is created successfully.» )
The output shows that the list is pickled successfully.
Example 2: Pickle a dictionary
Now, let’s pickle a Python dictionary object. A student dictionary is created and pickled using pickle.dump() function.
#declaring a student dictionary
std_dict = { ‘name’ : ‘John’ , ‘age’ : 22 , ‘class’ : ‘BS’ }
#pickling the dictionary and storing in a file
dictfile = open ( ‘dictPickle’ , ‘wb’ )
pickle . dump ( std_dict , dictfile )
print ( «The dictionary is pickled successfully.» )
The output shows that the dictionary is pickled successfully.
Example 3: Pickle a tuple
Now, let’s pickle a Python tuple object. A tuple object is created and pickled using pickle.dump() function.
my_tuple = ( ( 1 , 1 ) , ( 2 , 2 ) , ( 3 , 3 ) , ( 4 , 4 ) )
#pickling the dictionary and storing in a file
tuplefile = open ( ‘tuplePickle’ , ‘wb’ )
pickle . dump ( my_tuple , tuplefile )
print ( «The tuple is pickled successfully.» )
The output shows that the tuple object is pickled successfully.
Alright! That was all about pickling the different Python objects.
Python Unpickling Examples
Now, let’s see some examples for the Python unpickling process. We will unpickle all the Python objects that we have pickled in the previous examples. In the unpickling process, the pickled file is opened in the reading mode. The pickle.load() function is used to unpickle the Python object. The file object is passed as an argument to the pickle.load() function.
Example 1: Unpickle a list
The pickled list object is unpickled and assigned to a new list object.
#opening the listPickle file in reading mood
pickle_in = open ( ‘listPickle’ , ‘rb’ )
#unpickling the list and assigning to the list object
num_list = pickle . load ( pickle_in )
Example 2: Unpickle a dictionary
The pickled student dictionary object is unpickled and assigned to a new dictionary object.
#opening the dictPickle file in reading mood
pickle_in = open ( ‘dictPickle’ , ‘rb’ )
#unpickling the dict and assigning to the dictionary object
std_dict = pickle . load ( pickle_in )
Example 3: Unpickle a tupleOutput
The pickled tuple object is unpickled and assigned to a new tuple object.
#opening the tuplePickle file in reading mood
pickle_in = open ( ‘tuplePickle’ , ‘rb’ )
#unpickling the tuple and assigning to the dictionary object
std_dict = pickle . load ( pickle_in )
Conclusion
Pickle is a Python built-in module that is used to perform the serialization and deserialization operations. Serialization and deserialization are also known as pickling and unpickling, respectively. Through pickling, we can store the Python object in the form of a byte stream and later on retrieve it. The unpickling process refers to converting the pickled object into a Python object. This article explains the pickling and unpickling process with examples.
About the author
Kamran Sattar Awaisi
I am a software engineer and a research scholar. I like to write article and make tutorial on various IT topics including Python, Cloud Computing, Fog Computing and Deep Learning. I love to use Linux based operating systems.