Skip to content
Exercises · Q9

Q.Define pickling in Python. Explain serialization and deserialization of Python object.

Punjab PsebTextbookSubjective· 3mImportance★★★★★
59% · 13/22 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Pickling is Python's built-in mechanism to serialize objects into a byte stream for storage or transmission, and deserialize them back into Python objects.

What is Pickling?

Pickling is the process of converting a Python object hierarchy into a byte stream (a sequence of bytes) so that it can be stored in a file, sent over a network, or saved in a database. The reverse process—reconstructing the Python object from the byte stream—is called unpickling.

Python provides the pickle module for this purpose. Unlike text-based formats like JSON or CSV, pickle preserves the complete structure and type information of Python objects, including custom classes, nested data structures, and even functions (with limitations).

Serialization

Serialization is the process of converting a Python object into a byte stream. When you serialize an object, you transform its in-memory representation into a format that can be stored or transmitted.

The pickle.dump() method writes the serialized object directly to a file, while pickle.dumps() returns the serialized byte string.

import pickle

# Create a Python object (a dictionary with mixed types)
student = {
    'name': 'Arjun',
    'roll_no': 42,
    'marks': [85, 92, 78],
    'subjects': ('Physics', 'Chemistry', 'Maths')
}

# Serialization: write the object to a binary file
with open('student.pkl', 'wb') as file:
    pickle.dump(student, file)

print("Object serialized and saved to student.pkl")

Output:

Object serialized and saved to student.pkl

The file student.pkl now contains a binary representation of the student dictionary. The mode 'wb' (write binary) is essential because pickle produces bytes, not text.

Watch out

Always open pickle files in binary mode ('wb' for writing, 'rb' for reading). Opening in text mode will raise a TypeError.

Using pickle.dumps() for in-memory serialization

import pickle

data = [1, 2, 3, {'key': 'value'}]
serialized = pickle.dumps(data)

print(type(serialized))
print(serialized[:50])  # First 50 bytes

Output:

<class 'bytes'>
b'\x80\x04\x95\x1c\x00\x00\x00\x00\x00\x00\x00]\x94(K\x01K\x02K\x03}\x94\x8c\x03key\x94\x8c\x05value\x94se.'

The dumps() method returns a bytes object rather than writing to a file. This is useful when you need to send the serialized data over a network or store it in a database BLOB field.

Deserialization

Deserialization (unpickling) is the reverse process: reconstructing the original Python object from the byte stream.

The pickle.load() method reads from a file and returns the deserialized object, while pickle.loads() deserializes from a byte string.

import pickle

# Deserialization: read the object from the binary file
with open('student.pkl', 'rb') as file:
    restored_student = pickle.load(file)

print("Object deserialized from student.pkl")
print(restored_student)
print(type(restored_student))

Output:

Object deserialized from student.pkl
{'name': 'Arjun', 'roll_no': 42, 'marks': [85, 92, 78], 'subjects': ('Physics', 'Chemistry', 'Maths')}
<class 'dict'>

The deserialized object is an exact replica of the original, with all types and structure preserved. The list remains a list, the tuple remains a tuple, and the dictionary retains all its key-value pairs.

Using pickle.loads() for in-memory deserialization

import pickle

serialized = b'\x80\x04\x95\x1c\x00\x00\x00\x00\x00\x00\x00]\x94(K\x01K\x02K\x03}\x94\x8c\x03key\x94\x8c\x05value\x94se.'
data = pickle.loads(serialized)

print(data)

Output:

[1, 2, 3, {'key': 'value'}]

Why Pickling?

Pickling is the right tool when you need to:

  1. Preserve Python-specific types: Unlike JSON, pickle handles sets, tuples, custom objects, and even code objects. …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.