Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Understanding Python Pickling with example
Next article icon

Understanding Python Pickling with example

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Pickling-In-python-(1)
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

  1. 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.)
  2. 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.
  3. 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

  1. 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.
  2. 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.
  3. 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.


Next Article
Understanding Python Pickling with example

K

kartik
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    pickle — Python object serialization
    Python is a widely used general-purpose, high-level programming language. In this article, we will learn about pickling and unpickling in Python using the pickle module. The Python Pickle ModuleThe pickle module is used for implementing binary protocols for serializing and de-serializing a Python ob
    9 min read
    How to update a pickle file in Python?
    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 a disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, d
    3 min read
    How to search a pickle file in Python?
    Prerequisites: pickle file  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 that it “serializes” the object first before writing it to file. Pickling is a way to conver
    3 min read
    Difference Between Pickling and Unpickling in Python
    In this article, we will explore the key differences between pickling and unpickling in Python. We will discuss the concepts of Python pickling and unpickling in detail, including their purposes, syntax, usage, and considerations for safe and secure pickling and unpickling operations. Let's dive int
    3 min read
    Serializing Data Using the pickle and cPickle Modules
    Serialization is a process of storing an object as a stream of bytes or characters in order to transmit it over a network or store it on the disk to recreate it along with its state whenever required. The reverse process is called deserialization.  In Python, the Pickle module provides us the means
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences