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.
| Feature | Pickling | Unpickling |
|---|---|---|
| Definition | The process of converting a Python object into a byte stream (serialization). | The process of converting a byte stream back into a Python object (deserialization). |
| Purpose | To 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 Using | pickle.dump() or pickle.dumps() | pickle.load() or pickle.loads() |
| File Mode | Write mode — 'wb' (write binary). | Read mode — 'rb' (read binary). |
| Module Used | pickle | pickle |
| Output Type | Byte 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
- Pickled data is Python-specific — not readable by other programming languages.
- Never unpickle data from untrusted sources — it can execute malicious code.
- For secure serialization, consider using
jsonwhen 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
picklemodule usingdump(),load(),dumps(), andloads()methods. - Enables data persistence, object storage, and inter-process communication in Python.
