How to Use Pickle for Object Serialization in Python

Published on Aug. 22, 2023, 12:16 p.m.

To use Pickle for object serialization in Python, you can start by importing the pickle module. Once you have the pickle module imported, you can start pickling and unpickling objects easily.

Here’s an example code snippet that demonstrates how to use pickle to serialize and deserialize a Python object:

import pickle

# Define a Python object
my_object = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Serialize the object
serialized_object = pickle.dumps(my_object)

# Deserialize the object
deserialized_object = pickle.loads(serialized_object)

# Print the deserialized object
print(deserialized_object)

In this example, we first define a Python object, which is a dictionary. We then serialize the object using pickle.dumps() and store the serialized object in the serialized_object variable. Finally, we deserialize the object using pickle.loads() and store the deserialized object in the deserialized_object variable. We then print the deserialized object to verify that the pickling and unpickling worked correctly.

Note that Pickle can serialize a wide range of Python objects, including lists, tuples, dicts, and more. However, it’s important to be aware of the security implications of using Pickle, as it can deserialize potentially malicious objects as well. You should never unpickle data from an untrusted source without verifying its integrity first.

Tags: