How to use Pickle to save and load Variables in Python?
Last Updated :
27 May, 2025
Serialization is the process of converting an object’s state into a format that can be stored or transmitted and later reconstructed. Deserialization is the reverse process that convert the stored format back into an object. In Python, the pickle module provides a powerful way to serialize and deserialize Python objects, including custom classes, which formats like JSON cannot handle.
How to save variables with pickle
Pickle allows you to save Python objects so they can be reused later without losing their structure or data. This is done by converting objects into a byte stream that can be stored in memory or saved to a file.
1. Using dumps()
dumps() converts a Python object into a byte string stored in memory. It’s useful when you want to serialize data temporarily, for example, to send over a network or store in a database, without saving it to a file.
Python
import pickle
a = [{'This': 'is', 'Example': 1}, 'of', 'serialisation', ['using', 'pickle']]
res = pickle.dumps(a)
print(res)
Outputb'\x80\x04\x95K\x00\x00\x00\x00\x00\x00\x00]\x94(}\x94(\x8c\x04This\x94\x8c\x02is\x94\x8c\x07Example\x94K\x01u\x8c\x02of\x94\x8c\rserialisation\x94]\x94(\x8c\x05using\x94\x8c\x06pickle\x94ee.'
Explanation: pickle.dumps(a) converts this list into a byte stream, effectively serializing it into a binary format that can be stored or transferred. The result is assigned to the variable res.
2. Using dump()
dump() serializes a Python object and writes it directly to a file in binary format. This method is ideal for saving data permanently on disk so it can be loaded later.
Python
import pickle
a = [{'This': 'is', 'Example': 2}, 'of', 'serialisation', ['using', 'pickle']]
with open('file.pkl', 'wb') as file:
pickle.dump(a, file)
Output
Using dumpExplanation: with open('file.pkl', 'wb') as file: opens or creates a file in write binary mode and pickle.dump(a, file) serializes the list a and saves it to that file in binary format.
How to Load Variables with Pickle
Loading variables is just as important as saving them. Pickle lets you easily restore the saved byte stream or file back into the original Python objects, allowing your program to continue working with the data seamlessly.
1. Using loads()
loads() takes a byte string that represents a serialized Python object and converts it back into the original object in memory. Use this when you have serialized data in memory and want to recover the original Python structure.
Python
import pickle
a = [{'This': 'is', 'Example': 2}, 'of', 'serialisation', ['using', 'pickle']]
s = pickle.dumps(a)
res = pickle.loads(s)
print(res)
Output[{'This': 'is', 'Example': 2}, 'of', 'serialisation', ['using', 'pickle']]
Explanation: List a is serialized into a byte stream with pickle.dumps(a) and stored in s, then deserialized back to its original form using pickle.loads(s) and stored in res.
2. Using load()
load() reads serialized data from a binary file and reconstructs the original Python object in memory. It is used to load data previously saved using the dump() method.
Python
import pickle
with open('file.pkl', 'rb') as file:
a = pickle.load(file)
print(a)
Output
[{'This': 'is', 'Example': 2}, 'of', 'serialisation', ['using', 'pickle']]
Explanation: This code reads a binary file using pickle.load(file), which deserializes the data from file.pkl and restores the original Python object into the variable a, then prints it.
Related articles
Similar Reads
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
How to use Variables in Python3?
Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store
3 min read
How to save and load cookies in Selenium using Python
In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Pyth
4 min read
How to update a pickle file in Python?
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on a disk. What pickle does is that it âserializesâ the object first before writing it to file. Pickling is a way to convert a python object (list, d
3 min read
How to Use a Variable from Another Function in Python
Using a variable from another function is important for maintaining data consistency and code reusability. In this article, we will explore three different approaches to using a variable from another function in Python. Use a Variable from Another Function in PythonBelow are the possible approaches
2 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers].
2 min read
How to search a pickle file in Python?
Prerequisites: pickle file Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it âserializesâ the object first before writing it to file. Pickling is a way to conver
3 min read
How to Take a Tuple as an Input in Python?
Tuples are immutable data structures in Python making them ideal for storing fixed collections of items. In many situations, you may need to take a tuple as input from the user. Let's explore different methods to input tuples in Python.The simplest way to take a tuple as input is by using the split(
3 min read
Print Single and Multiple variable in Python
In Python, printing single and multiple variables refers to displaying the values stored in one or more variables using the print() function.Let's look at ways how we can print variables in Python:Printing a Single Variable in PythonThe simplest form of output is displaying the value of a single var
2 min read
Inserting variables to database table using Python
In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package.  import sqlite3 To see the operation on a database level just download the SQLite browser database.Note: For the
3 min read