Change language

Understanding Python Pickling with Example

|

The Python pickle module is used to serialize and deserialize the structure of Python objects. Any object in Python can be selected to be saved to disk. What pickle does is that it first "serializes" the object before writing it to a file. Pickling — it is a way of converting a Python object (list, dict, etc.) to a stream of characters. The idea is that this stream of symbols contains all the information needed to restore an object in another Python script.

# Python3 store illustration program
# effectively use the pickle module
# The module translates the Python object into memory
# into a serialized byte stream - a string
# bytes that can be written to any file-like object.

 

import pickle

 

def storeData ():

# data initialization for storage in the database

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

  

  # It’s important to use binary mode

dbfile = open ( ’examplePickle’ , ’ ab’ )

 

# source destination

pickle.dump (db, dbfile) 

dbfile.close ( )

 

def loadDa ta ():

# binary mode is also important for reading

dbfile = open ( ’examplePickle’ , ’rb’

  db = pickle.load (dbfile)

for keys in db:

print (keys, ’ =" ’ , db [keys])

< code class = "plain"> dbfile.close ()

 

if __ name__ = = ’ __main__’ :

storeData ()

loadData ()

Exit:

 omkarpathak-Inspiron-3542: ~ / Documents / Python-Programs $ python P60_PickleModule.py Omkar =" {’age’: 21, ’ name’: ’Omkar Pathak’, ’ key’: ’Omkar’, ’ pay’: 40000} Jagdish =" {’age’: 50, ’ name’: ’Jagdish Pathak’, ’ key’: ’Jagdish’, ’ pay’: 50000} 

Etching without file

# initializing data for storage in the database

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 storage

b = pickle.dumps (db)  # type (b) gives "class & # 39; bytes & # 39;"

 
# Download

myEntry = pickle.loads (b)

print (myEntry)

Benefits of using the Pickle Module:

  1. Recursive objects (objects containing references to themselves): Pickle tracks objects that it has already serialized, so later references to the same object will no longer be serialized. (The Marshall module is interrupted for this.)
  2. Sharing an object (references to the same object in different places): it’s like objects referencing themselves; pickle saves 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. Custom classes and their instances: Marshal doesn’t support them at all, but pickle can transparently save and restore class instances. The class definition must be importable and in the same module as when the object was saved.

This article is provided by Omkar Pathak . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically