Pickling and Unpickling are processes used in Python for object serialization — that is, converting Python objects into a format that can be stored or transferred, and then reconstructed later.

Python provides a built-in module called pickle to perform these operations.


FeaturePicklingUnpickling
DefinitionThe process of converting a Python object into a byte stream (serialization).The process of converting a byte stream back into a Python object (deserialization).
PurposeTo save Python objects to a file or send them over a network.To load or restore saved Python objects from a file or byte stream.
Performed Usingpickle.dump() or pickle.dumps()pickle.load() or pickle.loads()
File ModeWrite mode — 'wb' (write binary).Read mode — 'rb' (read binary).
Module Usedpicklepickle
Output TypeByte stream (binary data).Original Python object.

🧩 Example 1: Pickling an Object (Serialization)

import pickle

data = {"name": "Dheeraj", "age": 24, "skills": ["Python", "Cybersecurity", "Web Dev"]}

# Pickling the dictionary into a file
with open("data.pkl", "wb") as file:
    pickle.dump(data, file)

print("Data pickled successfully!")

Output:

Data pickled successfully!

Explanation:
The dictionary data is converted into a binary format and saved in the file data.pkl.


🧩 Example 2: Unpickling an Object (Deserialization)

import pickle

# Reading the pickled file
with open("data.pkl", "rb") as file:
    loaded_data = pickle.load(file)

print("Unpickled Data:", loaded_data)

Output:

Unpickled Data: {'name': 'Dheeraj', 'age': 24, 'skills': ['Python', 'Cybersecurity', 'Web Dev']}

Explanation:
The pickle.load() method reads the binary data and converts it back into the original Python dictionary.


🧩 Example 3: Using dumps() and loads()

import pickle

numbers = [1, 2, 3, 4, 5]

# Serialize (Pickle) to bytes
byte_data = pickle.dumps(numbers)
print("Pickled Byte Data:", byte_data)

# Deserialize (Unpickle) back to Python object
original_data = pickle.loads(byte_data)
print("Unpickled Object:", original_data)

Output:

Pickled Byte Data: b'\x80\x04\x95...\x94.'
Unpickled Object: [1, 2, 3, 4, 5]

⚠️ Important Notes

  1. Pickled data is Python-specific — not readable by other programming languages.
  2. Never unpickle data from untrusted sources — it can execute malicious code.
  3. For secure serialization, consider using json when data needs to be shared safely across different environments.

🔹 In Summary

  • Pickling → Serializing (saving) Python objects into byte streams.
  • Unpickling → Deserializing (loading) byte streams back into Python objects.
  • Handled by Python’s pickle module using dump(), load(), dumps(), and loads() methods.
  • Enables data persistence, object storage, and inter-process communication in Python.

Scroll to Top