Python Pickle | What is Pickle in python?

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure.

Pickling is the process whereby a Python object hierarchy is converted into a byte stream, and

UnPickling is the inverse operation, whereby a byte stream is converted back into an object hierarchy.

Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,”  or “flattening”.

However, to avoid confusion, the terms used here are “pickling” and “unpickling”.

Pickling in Python

#Pickling in Pythonimport pickleexample_dict = {'a': [1, 2.0, 3, 4+6j],'b': ('string', u'Unicode string'),'c': None}selfref_list = [1, 2, 3]selfref_list.append(selfref_list)selfref_listpickle_out = open("dict.pickle","wb") #writing in binary mode# Pickle dictionary using protocol 0.pickle.dump(example_dict, pickle_out) #use pickle.dump() to put the dict into opened file# Pickle the list using the highest protocol available.pickle.dump(selfref_list, pickle_out, -1)pickle_out.close()

unpickling in Python

#unpickling in Python#To read from a pickled fileimport pprint, picklepickle_in = open('dict.pickle', 'rb')data1 = pickle.load(pickle_in)pprint.pprint(data1)data2 = pickle.load(pickle_in)pprint.pprint(data2)pickle_in.close()