Understanding Python Pickling with example
Last Updated :
14 Aug, 2024
In Python, we sometimes need to save the object on the disk for later use. This can be done by using Python pickle. In this article, we will learn about pickles in Python along with a few examples.
Python Pickle — Python object serialization
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What Pickle does is it “serializes” the object first before writing it to a file. Pickling is a way to convert a Python object (list, dictionary, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another Python script. It provides a facility to convert any Python object to a byte stream. This Byte stream contains all essential information about the object so that it can be reconstructed, or “unpickled” and get back into its original form in any Python.
.png)
Working of a Serialization
Python Pickle Example
Pickling without a File
In this example, we will serialize the dictionary data and store it in a byte stream. Then this data is deserialized using pickle.loads() function back into the original Python object.
Python
import pickle
# initializing data to be stored in db
Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak',
'age' : 21, 'pay' : 40000}
Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak',
'age' : 50, 'pay' : 50000}
# database
db = {}
db['Omkar'] = Omkar
db['Jagdish'] = Jagdish
# For storing
# type(b) gives <class 'bytes'>;
b = pickle.dumps(db)
# For loading
myEntry = pickle.loads(b)
print(myEntry)
Output:
{'Omkar': {'key': 'Omkar', 'name': 'Omkar Pathak', 'age': 21, 'pay': 40000},
'Jagdish': {'key': 'Jagdish', 'name': 'Jagdish Pathak', 'age': 50, 'pay': 50000}}
Pickling with a File
In this example, we will use a pickle file to first write the data in it using the pickle.dump() function. Then using the pickle.load() function, we will load the pickle fine in Python script and print its data in the form of a Python dictionary.
Python
# Python3 program to illustrate store
# efficiently using pickle module
# Module translates an in-memory Python object
# into a serialized byte stream—a string of
# bytes that can be written to any file-like object.
import pickle
def storeData():
# initializing data to be stored in db
Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak',
'age' : 21, 'pay' : 40000}
Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak',
'age' : 50, 'pay' : 50000}
# database
db = {}
db['Omkar'] = Omkar
db['Jagdish'] = Jagdish
# Its important to use binary mode
dbfile = open('examplePickle', 'ab')
# source, destination
pickle.dump(db, dbfile)
dbfile.close()
def loadData():
# for reading also binary mode is important
dbfile = open('examplePickle', 'rb')
db = pickle.load(dbfile)
for keys in db:
print(keys, '=>', db[keys])
dbfile.close()
if __name__ == '__main__':
storeData()
loadData()
Output:
Omkar => {'key': 'Omkar', 'name': 'Omkar Pathak', 'age': 21, 'pay': 40000}
Jagdish => {'key': 'Jagdish', 'name': 'Jagdish Pathak', 'age': 50, 'pay': 50000}
Advantages of Using Pickle in Python
- Recursive objects (objects containing references to themselves): Pickle keeps track of the objects it has already serialized, so later references to the same object won’t be serialized again. (The marshal module breaks for this.)
- Object sharing (references to the same object in different places): This is similar to self-referencing objects. Pickle stores the object once, and ensures that all other references point to the master copy. Shared objects remain shared, which can be very important for mutable objects.
- User-defined classes and their instances: Marshal does not support these at all, but Pickle can save and restore class instances transparently. The class definition must be importable and live in the same module as when the object was stored.
Disadvatages of Using Pickle in Python
- Python Version Dependency: Data of picle is so sensitive to the version of Python that produced. Pickled object created with one version of Python that might not be unpickled with a various versions.
- Non-Readble: The format of pickle is binary and not easily readable or editable by humans. The contracts that are in JSON or XML format can be easily modified.
- Large data inefficiency: Large datasets can slow down the pickling and unpickling. Serialization might be more appropriate for such use-cases.
Conclusion
While Python Pickle offers capabilities for object serialization, developers that maintain limitations , especially while working across various Python versions or dealing with the large datasets. It’s important to remember always consider the specific needs of your application to determine if ickle or an alternative like JSON, XML is suited for serialization.
Understanding Python Pickling with example – FAQs
What is Pickling in Python with an Example?
Pickling in Python refers to the process of converting a Python object into a byte stream, which can be stored on disk or sent over a network. This byte stream can later be converted back into the original object, a process known as unpickling. The pickle module in Python provides this functionality.
Example of Pickling and Unpickling:
import pickle
# Define a sample dictionary
data = {'a': [1, 2.0, 3, 4+6j],
'b': ("character string", b"byte string"),
'c': {None, True, False}}
# Pickling the dictionary
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Unpickling the dictionary
with open('data.pkl', 'rb') as f:
data_loaded = pickle.load(f)
print(data_loaded)
What is the Pickle Load Function?
The pickle.load() function in Python reads a pickled object representation from an open file object and returns the reconstituted object hierarchy specified therein. This is used for deserializing objects stored in files or received over a network.
What Objects Cannot Be Pickled in Python?
Most Python object types can be pickled, but there are a few exceptions:
- Objects containing file handles, sockets, database connections, and other system-related resources are not picklable.
- Objects defined in the main module can be pickled, but their class definitions cannot be pickled across different sessions. For instance, you cannot pickle a class instance, close your Python session, start a new one, and expect to unpickle your instance unless the class definition is part of an importable module.
- Objects involving thread locks or synchronization primitives (like
threading.Lock) cannot be pickled. - Custom objects that maintain state with dynamic attributes or those that override serialization methods and don’t call the superclass methods may also pose problems.
How to Convert a Model to Pickle in Python?
Converting a machine learning model or any Python object to a pickle involves using the pickle module to serialize the object. Here’s how you can do it:
import pickle
from sklearn.ensemble import RandomForestClassifier
# Train a sample model
model = RandomForestClassifier()
model.fit(X_train, y_train) # Assume X_train and y_train are defined
# Pickle the model
with open('model.pkl', 'wb') as file:
pickle.dump(model, file)
# To load the model back
with open('model.pkl', 'rb') as file:
loaded_model = pickle.load(file)
Is Joblib Better than Pickle?
For machine learning models, joblib is often better than pickle:
- Efficiency:
joblib is more efficient for objects that carry large numpy arrays internally as is often the case for fitted scikit-learn estimators. - Compression:
joblib can compress the resulting files, which can save space when dealing with large models. - Speed:
joblib can be faster than pickle when dealing with complex objects like machine learning models that contain a lot of parameters.
However, pickle is more general and a part of the Python standard library, which makes it more universally applicable. joblib is optimized for scenarios typical in machine learning but isn’t as versatile as pickle.
Similar Reads
How to set height equal to dynamic width (CSS fluid layout) ?
To create a fluid layout in CSS, set an element's height to the same value as its dynamic width. This makes the layout more adaptable and responsive since the element's height will automatically change depending on the viewport's width. It is possible to determine the element's height by using the p
2 min read
How to Set Height Equal to Dynamic Width (CSS fluid layout) in JavaScript ?
A key component of constructing a contemporary website in web development is developing an adaptable and dynamic layout. Setting the height of an element equal to its dynamic width, often known as a CSS fluid layout, is a common difficulty in accomplishing this. When the screen size changes and you
4 min read
How to Create Equal Height Columns in CSS ?
Equal Height Columns in CSS refer to ensuring that multiple columns in a layout have the same height, regardless of the content inside each column. This can be achieved using modern CSS techniques like Flexbox, CSS Grid, or the Table display property. Table of Content Using FlexUsing GridUsing Table
3 min read
How to make div height expand with its content using CSS ?
When designing a webpage, ensuring that a div adjusts its height according to its content is important for creating a flexible and responsive layout. By using CSS, you can easily make a div adapt to varying content sizes, which is particularly useful when dealing with dynamic or unpredictable conten
3 min read
How to Set Viewport Height & Width in CSS ?
Set viewport height and width in CSS is essential for creating responsive and visually appealing web designs. We'll explore the concepts of setting viewport height and width by using various methods like CSS Units, Viewport-Relative Units, and keyframe Media Queries. Table of Content Setting viewpor
3 min read
How to Stretch Elements to Fit the Whole Height of the Browser Window Using CSS?
To stretch elements to fit the whole height of the browser window using CSS, you can use "vh" units, where "1vh" equals 1% of the viewport height, so setting the height to "100vh" spans the entire height. Approach: Using CSS height PropertyIn this approach, we are using the Height property to fit th
1 min read
How to get the height of device screen in JavaScript ?
Given an HTML document which is running on a device. The task is to find the height of the working screen device using JavaScript. Prerequisite - How to get the width of device screen in JavaScript ? Example 1: This example uses window.innerHeight property to get the height of the device screen. The
2 min read
How to fit text container width dynamically according to screen size using CSS ?
In this article, we have given a text paragraph and the task is to fit the text width dynamically according to screen size using HTML and CSS. Some of the important properties used in the code are as follows- display-grid: It helps us to display the content on the page in the grid structure.grid-gap
7 min read
How to Adjust the Width and Height of an iframe to Fit the Content Inside It?
When using the <iframe> tag in HTML, the content inside the iframe is displayed with a default size if the width and height attributes are not specified. Even if the dimensions are specified, it can still be difficult to perfectly match the iframe’s size with the content inside it. This can be
4 min read
jQWidgets jqxLayout height Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxLayout is used for representing a jQuery widget that is used for the creation of complex layouts with nested
2 min read
How to Make Flexbox Items of Same Size Using CSS?
To make Flexbox items the same size using CSS, you can use various properties to control the dimensions of the items and ensure consistency in layout. By default, Flexbox items can have different sizes based on their content, but with a few CSS changes, you can make them uniform. 1. Using Flex Prope
5 min read
How to Specify Height to Fit-Content with Tailwind CSS ?
Specifying height to fit-content in Tailwind CSS means setting an element’s height to automatically adjust based on its content. Tailwind provides the h-fit utility class, which ensures the element's height dynamically adapts to its content's size. Adjusting Height with h-fit in Tailwind CSSThis app
2 min read
How to detect the change in DIV's dimension ?
The change in a div's dimension can be detected using 2 approaches: Method 1: Checking for changes using the ResizeObserver Interface The ResizeObserver Interface is used to report changes in dimensions of an element. The element to be tracked is first selected using jQuery. A ResizeObserver object
4 min read
How to Change the Height and Width of an Element with JavaScript?
To change the height and width of an element using JavaScript, you can directly manipulate the style property of the element. Here’s a simple guide on how to do it: Example:[GFGTABS] HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <m
1 min read
Primer CSS Layout width and height
Primer CSS is a free open-source CSS framework that is built with the GitHub design system to provide support to the broad spectrum of Github websites. It creates the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are ste
5 min read
How to Create Equal Width Table Cell Using CSS ?
Creating equal-width table cells using CSS refers to adjusting the table's layout so that all columns maintain the same width. This technique ensures a consistent and organized appearance, making the table content easier to read and visually balanced. Here we are following some common approaches: Ta
3 min read
How to Set Width and Height of Span Element using CSS ?
The <span> tag is used to apply styles or scripting to a specific part of text within a larger block of content. The <span> tag is an inline element, you may encounter scenarios where setting its width and height becomes necessary. This article explores various approaches to set the widt
2 min read
How to Set 100% Height with Padding/Margin in CSS ?
In this article, we'll explore CSS layouts with 100% width/height while accommodating padding and margins. In the process of web page design, it is often faced with scenarios where the intention is to have an element fill the entire width and/or height of its parent container, while also maintaining
3 min read
How to give a div tag 100% height of the browser window using CSS
CSS allows to adjustment of the height of an element using the height property. While there are several units to specify the height of an element. Set the height of a <div> to 100% of its parent container with height: 100%, or use height: 100vh; for a full viewport height, ensuring the <div
2 min read