
Domains
Artificial Intelligence
Harness AI to create smarter workflows and scalable growth.
View All Artificial Intelligence Coursesicon-aiCertifications
Certification
100+ Hours
Trending
Post Graduate Certification Program in Data Analytics and Applied AICertification
140+ Hours
Trending
Executive Post Graduate Certificate in Data Science and Applied AICertification
140+ Hours
Trending
PG Certificate in Applied Generative Engineering & LLM ApplicationsCertification
150+ Hours
Trending
PG Certificate in AI Powered Product and Design ThinkingCertification
15 Weeks
Trending
AI Masters ProgramCertification
4 Weeks
Trending
Vibe Coding 101: No-code AI ProgrammingCertification
48 Hours
Trending
Applied Agentic AI - No CodeCertification
16 Hours
Trending
Generative AI and Prompt EngineeringCertification
8 Weeks
Trending
AI-Powered Product ManagementCertification
8 Weeks
Trending
Applied Agentic AI CertificationCertification
16 Hours
Generative AI Course for Scrum MastersCertification
16 Hours
Generative AI Course for Project ManagersCertification
16 Hours
Generative AI Course for POPMCertification
16 Hours
Gen AI Course for Business AnalystsCertification
16 Hours
AI Powered Software DevelopmentCertification
16 Hours
AI-Data Analytics with Power BICertification
16 Hours
AI-Driven Digital Marketing TrainingCertification
16 Hours
Gen AI for Enterprise AgilistAdvanced Certifications
Masters
Executive Diploma
Executive Diploma in Machine Learning and AIExecutive Diploma
Executive Diploma in Data Science & Artificial Intelligence from IIITBCertification
Chief Technology Officer & AI Leadership ProgrammeMaster's Degree
Master of Science in Machine Learning & AIDual Certification
Executive Programme in Generative AI for LeadersCertification
Executive Post Graduate Programme in Applied AI and Agentic AIExecutive PG Program
IIT KGP-Executive PG Certificate in Gen AI and AgenticSelf-Learning Courses
Universal AI by MIT Open LearningAgile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
AI-Empowered SAFe® 6.0 Scrum MasterPMI
21 Hours
Best Seller
PMI Agile Certified Practitioner (PMI-ACP) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
AI-Empowered SAFe® 6 Release Train Engineer (RTE) CourseScaled Agile, Inc.
16 Hours
Trending
SAFe® AI-Empowered Product Owner/Product Manager (6.0)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterProduct OwnerSAFe AgilistAgile CoachAccreditation Bodies
Scrum AllianceScaled Agile, Inc.Scrum.orgICAgilePMITop Resources
Scrum TutorialCSM VS CSPOCSM vs PSMScrum Practice TestPO Interview QsProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationPMI
23 Hours
Best Seller
Certified Associate in Project Management (CAPM)®PMI
24 Hours
Best Seller
Program Management Professional (PgMP®)PMI
24 Hours
Best Seller
Portfolio Management Professional (PfMP)®PMI
30 Hours
Best Seller
Project Management Institute-Risk Management Professional (PMI-RMP)®Skills
Change ManagementProject Management TechniquesCertified Associate in Project Management (CAPM) CertificationOracle Primavera P6 CertificationMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CoursePRINCE2 Foundation CourseRoles
Project ManagerProgram Management ProfessionalPortfolio Management ProfessionalAccreditation Bodies
PMIAxelosScrum AllianceTop Resources
Theories of MotivationManagement ProcessProject Manager Intvw QsWhat is PMP?PMP Practice TestCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v13) CertificationISACA
40 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) CertificationISACA
16 Hours
COBIT5 FoundationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityIT Security Thesis TopicEthical Hacking Intvw QsCybersecurity in BankingBasics of CybersecurityCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramRoles
Cloud EngineerCloud ArchitectOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAWS Certified DevOps EngineerAWS Certified Solutions Architect AssociateMicrosoft Certified Azure Data Engineer AssociateMicrosoft Azure Administrator (AZ-104) CourseAWS Certified SysOps Administrator AssociateMicrosoft Certified Azure Developer AssociateAWS Certified Cloud PractitionerAuthorized Partners of
AWSMicrosoftTop Resources
Scrum TutorialCSM VS CSPOCSM vs PSMScrum Practice TestPO Interview QsIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All ITSM Coursesicon-git-commitCertifications
Axelos
16 Hours
New
ITIL Foundation (Version 5) CertificationAxelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
8 Hours
New
ITIL Foundation Bridge Course (Version 5)PeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamITIL 4 Specialist: Drive Stakeholder Value (DSV) CourseITIL 4 Strategist: Direct, Plan, and ImproveITIL 4 FoundationTop Resources
ITIL Practice TestITSM Key ConceptsWhat is ITIL?Top SysAdmin SkillsTop Service-based FirmsData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataOur Courses
Data Science with PythonSQL For Data AnalyticsRoles
Data ScientistData AnalystData EngineerAI EngineerOn-Demand Courses
Data Analysis Using ExcelDeep Learning with Keras and TensorFlowDeployment of Machine Learning ModelsFundamentals of Reinforcement LearningIntroduction to Cutting-Edge AI with TransformersMachine Learning with PythonMaster Python: Advance Data Analysis with PythonMaths and Stats FoundationNatural Language Processing (NLP) with PythonPython for Data ScienceSQL for Data Analytics CoursesAI Advanced: Computer Vision for AI ProfessionalsMaster Applied Machine LearningMaster Time Series Forecasting Using PythonTop Resources
Machine Learning TutorialData Science Interview QuestionsDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesDocker with KubernetesJenkinsRoles
DevOps EngineerDevOps ExpertOn-Demand Courses
CI/CD with Jenkins XDevOps Using JenkinsCI-CD and DevOpsDocker & KubernetesDevOps Fundamentals Crash CourseMicrosoft Certified DevOps Engineer ExpertAnsible for Beginners: The Complete Crash CourseContainer Orchestration Using KubernetesContainerization Using DockerMaster Infrastructure Provisioning with TerraformGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsDevOps Practice TestDevOps Interview QsGit TutorialBasic Docker CommandsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingData Analysis Using ExcelTop Resources
Python Data Viz LibsSpotfire Interview QsTop Benefits of Power BIPower BI Dev FutureWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeOur Courses
ReactNode JSAngularOn-Demand Courses
Angular TrainingBasics of Spring Core and MVCFront-End Development BootcampReact JS TrainingSpring Boot and Spring CloudMongoDB Developer CourseTop Resources
Top HTML ProjectsFED Interview QsReact Native Interview QsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideIntroduction to DeFiTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptData Structures and Algorithms with Java: The Practical GuideLinux Essentials for Developers: The Complete MasterclassMaster Git and GitHubMaster Java Programming LanguageProgramming Essentials for BeginnersSoftware Engineering Fundamentals and Lifecycle (SEFLC) CourseTest-Driven Development for Java ProgrammersTypeScript: Beginner to AdvancedTop Resources
Python TutorialR Programming TutorialSpring Boot Interview QsObject serialization is the process of converting state of an object into byte stream. This byte stream can further be stored in any file-like object such as a disk file or memory stream. It can also be transmitted via sockets etc. Deserialization is the process of reconstructing the object from the byte stream.
Python refers to serialization and deserialization by terms pickling and unpickling respectively. The 'pickle' module bundled with Python’s standard library defines functions for serialization (dump() and dumps()) and deserialization (load() and loads()).
The data format of pickle module is very Python specific. Hence, programs not written in Python may not be able to deserialize the encoded (pickled) data properly. In fact it is not considered to be secure to unpickle data from unauthenticated source.
Protocols are the conventions used in constructing and deconstructing Python objects to/from binary data. Currently pickle module defines 5 different protocols as listed below:
Protocol version 0 | Original “human-readable” protocol backwards compatible with earlier versions. |
Protocol version 1 | Old binary format also compatible with earlier versions of Python. |
Protocol version 2 | Introduced in Python 2.3 provides efficient pickling of new-style classes. |
Protocol version 3 | Added in Python 3.0. recommended when compatibility with other Python 3 versions is required. |
Protocol version 4 | was added in Python 3.4. It adds support for very large objects |
To know highest and default protocol version of your Python installation use following constants defined in pickle module
>>> import pickle
>>> pickle.HIGHEST_PROTOCOL
4
>>> pickle.DEFAULT_PROTOCOL
3
The dump() and load() functions of pickle module respectively perform pickling and unpickling of Python data. The dump() function writes pickled object to a file (or file like object) and load() function unpickles data from file back to Python object.
Following program pickle a dictionary object into a binary file.
import pickle
f=open("pickled.txt","wb")
dct={"name":"Rajeev", "age":23, "Gender":"Male","marks":75}
pickle.dump(dct,f)
f.close()
When above code is executed, the dictionary object’s byte representation will be stored in 'pickled.txt' file. The file must have 'write and binary' mode enabled.
On the other hand load() function unpickles or deserializes data from binary file back to Python dictionary. Run following script
import pickle
f=open("pickled.txt","rb")
d=pickle.load(f)
print (d)
f.close()
Python console shows the dictionary object read from file
{'age': 23, 'Gender': 'Male', 'name': 'Rajeev', 'marks': 75}
Note that the dictionary object doesn't retain order of insertion of keys. Hence the k-v pairs in retrieved dictionary may not be in original order.
The pickle module also consists of dumps() function that pickles Python data to a string representation.
>>> from pickle import dump
>>> dct={"name":"Rajneesh", "age":23, "Gender":"Male","marks":75}
>>> dctstring=dumps(dct)
>>> dctstring
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x04\x00\x00\x00Raviq\x02X\x03\x00\x00\x00ageq\x03K\x17X\x06\x00\x00\x00Genderq\x04X\x01\x00\x00\x00Mq\x05X\x05\x00\x00\x00marksq\x06KKu.'
Use loads() function to unpickle the string and obtain original dictionary object.
>>> from pickle import load
>>> dct=loads(dctstring)
>>> dct
{'name': 'Rajneesh', 'age': 23, 'Gender': 'Male', 'marks': 75}
In addition to above convenience functions, the pickle module also defines Pickler and Unpickler classes. Pickler class has dump() method that writes pickle data to a binary file. Unpickler class reads binary data from file and constructs Python object.
To write Python object’s pickled data
from pickle import pickler
f=open("pickled.txt","wb")
dct={'name': 'Rajneesh', 'age': 23, 'Gender': 'Male', 'marks': 75}
Pickler(f).dump(dct)
f.close()
To read back data by unpickling binary file from pickle import Unpickler
f=open("pickled.txt","rb")
dct=Unpickler(f).load()
print (dct)
f.close()
Just as objects of Python standard data types are picklable, similarly, objects of custom class can also be pickled and unpickled.
from pickle import *
class student:
def __init__(self):
self.name="XYZ"
self.age=22
def show(self):
print ("name:", self.name, "age:", self.age)
p1=person()
f=open("pickled.txt","wb")
dump(p1,f)
f.close()
print ("unpickled data")
f=open("pickled.txt","rb")
p1=load(f)
p1.show()
Python library also contains 'marshal' module that is used b Python interpreter itself for internal serialization of Python objects.
The marshal module in Python’s standard library provides object serialization features (similar to pickle module). However it is not really useful for general purpose data persistence in files or transmission of Python objects through sockets etc. This module is internally used by Python interpreter itself to perform read/write operations on compiled versions of Python modules (.pyc files). The data format used by marshal module keeps on changing and is not compatible across Python versions (not even sub versions). That’s the reason a compiled Python script (.pyc file) of one version most probably won’t execute on another. The marshal module is thus used for Python’s internal object serialization.
Similar to pickle module, marshal module also defines load() and dump() functions for reading and writing marshalled objects from / to file. Also loads() and dumps() function deal with string representation of marshalled object.
Following code shows a Python dictionary object marshalled using dumps(). The byte representation is converted back to dictionary by loads() function.
import marshal
person={"name":"Krishna", "age":22, "marks":[45,56,78]}
data=marshal.dumps(person)
obj= marshal.loads(data)
print (obj)
As mentioned above marshal module is used by interpreter to process .pyc files. Following example demonstrates use of dump() and load() functions to handle Python code objects, which are used to store precompiled Python modules.
The code uses built-in compile() function to build a code object out of a source string which embeds Python instructions.
compile(source, file, mode)
The file parameter should be the file from which the code was read. If it wasn’t read from a file pass any arbitrary string.
The mode parameter is set to ‘exec’ if the source contains sequence of statements or ‘eval’ if there is a single expression or ‘single’ if it contains a single interactive statement.
The compile code object is then stored in a .pyc file using dump() function
import marshal
string = """
a=10
b=20
print ('multiplication=',a*b)
"""
code = compile(string, "script", "exec")
f=open("marshal.pyc","wb")
marshal.dump(code, f)
f.close()
To deserialize the object from .pyc file use load() function. Since it returns a code object, it can be run using exec(), another built-in function.
import marshal
f=open("marshal.pyc","rb")
data=marshal.load(f)
exec (data)
The output will be result of code block embedded in source string
multiplication= 200
Another module called 'shelve' in Python’s standard library is a simple yet effective tool for persistent data storage when you don't really need a relational database solution. The 'Shelf' object defined in this module is dictionary-like object which is persistently stored in a disk file. This creates a file similar to dbm database on UNIX like systems. However, object of only string type is allowed as key in this special dictionary object, value however can be any picklable object.
The shelve module defines three classes as follows:
Shelf | This is the base class for shelf implementations. It is initialized with dict-like object. |
BsdDbShelf | This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods. |
DbfilenameShelf | This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object. |
Easiest way to form a Shelf object is to use open() function defined in shelve module which return a DbfilenameShelf object.
shelve.open(filename, flag='c', protocol=None, writeback=False)
The filename parameter is used as name of the database created.
Default value for flag parameter is ‘c’ for read/write access. Other flags are ‘w’ (write only) ‘r’ (read only) and ‘n’ (new with read/write)
Protocol parameter denotes pickle protocol enlisted earlier.
writeback parameter by default is false. If set to true, the accessed entries are cached. Every access calls sync() and close() operations hence process may be slow.
Following code creates a database and stores dictionary entries in it.
import shelve
s=shelve.open("test")
s['name']="Ajay"
s['age']=23
s['marks']=75
s.close()
This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available:
close() | Synchronise and close persistent dict object. |
sync() | Write back all entries in the cache if shelf was opened with writeback set to True. |
get() | Returns value associated with key |
items() | list of tuples – each tuple is key value pair |
keys() | list of shelf keys |
pop() | Remove specified key and return the corresponding value. |
update() | Update shelf from another dict/iterable |
values() | list of shelf values |
To access value of a particular key in shelf:
>>> s=shelve.open('test')
>>> s['age']
23
>>> s['age']=25
>>> s.get('age')
25
The items(), keys() and values() methods return view objects.
>>> list(s.items())
[('name', 'Ajay'), ('age', 25), ('marks', 75)]
>>> list(s.keys())
['name', 'age', 'marks']
>>> list(s.values())
['Ajay', 25, 75]
To remove a key-value pair from shelf
>>> s.pop('marks')
75
>>> list(s.items())
[('name', 'Ajay'), ('age', 25)]
Notice that key-value pair of marks-75 has been removed.
To merge items of another dictionary with shelf use update() method
>>> d={'salary':10000, 'designation':'manager'}
>>> s.update(d)
>>> list(s.items())
[('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')]
There is another popular serialization/deserialization format called JSON which stands for JavaScript Object Notation. It is a lightweight data interchange format. It is similar to pickle. However, pickle serialization is Python specific whereas JSON format is implemented by many languages. The 'json' module in Python’s standard library defines functions for object serialization.
Just as in pickle module, the json module also provides dumps() and loads() function for serialization of Python object into JSON encoded string. The dump() and load() functions write and read serialized Python objects to/from file.
This function converts the object into JSON format.
This function converts a JSON string back to Python object.
Following example demonstrates basic usage of these functions:
>>> import json
>>> data=['Rakhee',{'marks':(50,60,70)}]
>>> s=json.dumps(data)
>>> s
'["Rakhee", {"marks": [50, 60, 70]}]'
>>> json.loads(s)
['Rakhee', {'marks': [50, 60, 70]}]
Th dumps() function can take optional sort_keys argument. By default it is False. If set to True, the dictionary keys appear in sorted order in the JSON string.
>>> data={"marks":50, "age":20, "rank":5}
>>> s=json.dumps(data, sort_keys=True)
>>> s
'{"age": 20, "marks": 50, "rank": 5}'
>>> json.loads(s)
{'age': 20, 'marks': 50, 'rank': 5}
The dumps() function has another optional parameter called indent which takes a number as value. It decides length of each segment of formatted representation of json string, similar to pprint output.
>>> data=['Rakesh',{'marks':(50,60,70)}]
>>> s=json.dumps(data, indent=2)
>>> print (s)
[
"Rakesh",
{
"marks": [
50,
60,
70
]
}
]
The json module also has object oriented interface corresponding to above convenience functions. There are two classes defined in the module – JSONEncoder and JSONDecoder.
Object of this class is encoder for Python data structures. Each Python data type is converted in corresponding JSON type as shown in following table:
Python | JSON |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
The JSONEncoder class is instantiated by JSONEncoder() constructor. Following important methods are defined in encoder class:
encode(): serializes Python object into JSON format
iterencode(): Encodes the object and returns an iterator yielding encoded form of each item in the object.
indent: Determines indent level of encoded string
sort_keys: is either true or false to make keys appear in sorted order or not.
Check_circular: if True, check for circular reference in container type object
Following example encodes Python list object.
>>> e=json.JSONEncoder()
>>> e.encode(data)
'["Rakhee", {"marks": [50, 60, 70]}]'
Using iterencode() method, each part of the encoded string is displayed as below:
>>> for obj in e.iterencode(data):
print (obj)
["Rakhee"
,
{
"marks"
:
[50
, 60
, 70
]
}
]
Object of this class helps in decoded in json string back to Python data structure. Main method in this class is decode(). Following example code retrieves Python list object from encoded string in earlier step.
>>> d=json.JSONDecoder()
>>> d.decode(s)
['Rakhee', {'marks': [50, 60, 70]}]
The json module defines load() and dump() functions to write JSON data to a file like object – which may be a disk file or a byte stream and read data back from them.
This function encodes Python object data in JSON format and writes it to a file. The file must be having write permission.
>>> data=['Rakhee', {'marks': (50, 60, 70)}]
>>> fp=open('json.txt','w')
>>> json.dump(data,fp)
>>> fp.close()
This code will create ‘json.txt’ in current directory. It shows the contents as follows:
["Rakhee", {"marks": [50, 60, 70]}]
This function loads JSON data from the file and constructs Python object from it. The file must be opened with read permission.
>>> fp=open('json.txt','r')
>>> ret=json.load(fp)
>>> ret
['Rakhee', {'marks': [50, 60, 70]}]
>>> fp.close()