Frequently Asked Questions

What is pickling and unpickling in Python?

We may need to save an object created. Pickling files and objects is a good method to save data for later use.


The process of converting any kind of object into byte streams is called pickling. The other names for pickling are serialization, flattening or marshalling.


The byte streams generated through pickling can be reverted back to the objects. This process is called Unpickling.

Let us learn the python code to make use of pickling and unpickling.

How to Use Pickle to Save and Load Variables in Python?

Variables of different types can be saved and loaded in python.

Install Pickle

pip install pickle

Save Data in Pickle File

import pickle
fruits = {1:"apple",2:"banana",3:"guava",4:"guava"}
fb = open("fruits.pickle","wb")
pickle.dump(fruits, fb)

In the above code, we are pickling a dictionary and saving it in fruits.pickle file.  Similarly, any object can be pickled in python.

Load Data From Pickle

import pickle
pickle_obj = open("fruits.pickle", 'rb')
fruits = pickle.load(pickle_obj)

fruits = {1:”apple”,2:”banana”,3:”guava”,4:”guava”}

In the above code, we are reading the pickled file in the fruits variable.

Pros of Pickling

  • Easy to use.
  • Complicated data can be saved easily.
  • Reading pickle file is not easy and thus provide some security.

Cons of Pickling

  • Pickled python objects cannot be used in any other programming language.
  • Major issues can be caused if data is unpickled from a malicious source.

Other Popular Questions