How to serialize object, list and dictionary in Python with Examples

Serialization is a process in which an object is converted into a stream of bytes and then saved to a file. In Python, serialization is known as pickling. In order to perform serialization, you need to use built-in pickle module.

Steps to perform serialization in Python

  1. First of all, import pickle module.
    import pickle
  2. Open the file in which you want to save the object in binary write mode.
    outputFile = open('filename', 'wb')
  3. Call pickle's dump() method and pass object as a first argument and the above-created file object as a second argument.
    pickle.dump(object, outputFile)
  4. Repeat step 3 until all of the objects are saved to a file.
  5. Close the file by calling close() function.
    outputFile.close()

Note: You can serialize any Python data structure such as dictionaries, tuples, lists, integer numbers, strings, sets, and floating-point numbers.

Example: How to serialize object in Python

#Python Program to serialize object
import pickle

#Employee class
class Employee:
   #Constructor
   def __init__(self, name, empid, salary):
      self.name = name
      self.empid = empid
      self.salary = salary

#Opened the employee.dat file in write binary mode
outputFile = open('employee.dat', 'wb')
e1 = Employee('Keshav', 1, 50000)#e1 is an Employee class object
e2 = Employee('Madhav', 2, 55000)#e2 is an Employee class object
e3 = Employee('Govind', 3, 45000)#e3 is an Employee class object

pickle.dump(e1, outputFile)#Calling dump() function to serialize e1 object
pickle.dump(e2, outputFile)#Calling dump() function to serialize e2 object
pickle.dump(e3, outputFile)#Calling dump() function to serialize e3 object

outputFile.close()#Close the file

When you run the above code, you will get employee.dat file. The content of this file is

Serialize object in Python

Example: How to serialize dictionary in Python

#Python Program to serialize dictionary
import pickle

dict = {'brand': 'Samsung', 'model': 'Galaxy A7', 'price': 21990}
outputFile = open('mobile.dat', 'wb')
pickle.dump(dict, outputFile)
outputFile.close()

When you run the above code, you will get mobile.dat file. The content of this file is

Serialize dictionary in Python

Example: How to serialize list in Python

#Python Program to serialize list
import pickle

list = ['Python', 'Numpy', 'Pandas']
outputFile = open('programming.dat', 'wb')
pickle.dump(list, outputFile)
outputFile.close()

On running the above code, you will obtain programming.dat file. The content of this file is

Serialize list in Python

Recommended Posts