Computer >> Computer tutorials >  >> Programming >> Python

Understanding Python Pickling with example


In this article, we will learn about pickling different data types in Python. We can pickle Booleans, Integers, Floats, Complex numbers, Strings, Tuples, Lists, Sets, and dictionaries that contain pickable objects. Some entities like generators, inner local classes, lambda functions can’t be pickled.

What is pickling?

Pickling involves a continous cycle of serializing and de-serializing Python entities of object type and related structures, also referred to as marshalling or flattening.This involves conversion of an object located in memory into a form of bytes that may be stored on disk or sent over to a local network.

Constraints in its usage?

When we want to share data using different programming languages, the use of pickle modules is not preferred. This means that cross-platform compatibility is not guaranteed.

Pickling can be done on raw data without file handling.In this module, we will learn how we can pickle raw data into binary files by the process of serialization.

Example

# Python pickling
import pickle as pk
def learnData():
   # data to be stored in database
   dict_1 = {'tutorial':'point','Python':'3.x'}
   dict_2 = {'Data
structure':'dictionary','pickling':'serialization'}
   # database
   db = {}
   db['1'] = dict_1
   db['2'] = dict_2
   # binary file open using filepointer in append mode
   fp = open('Newfile', 'ab')
   # source, destination
   pk.dump(db, fp)
   fp.close()
def displayData():
   # binary file open using filepointer in read mode
   fp = open('Newfile', 'rb')
   db = pk.load(fp)
   for i in db:
      print(i, '=>', db[i])
   fp.close()
if __name__ == '__main__':
   learnData()
   displayData()

Output

dict_1 = {'tutorial':'point','Python':'3.x'}
dict_2 = {'Data structure':'dictionary','pickling':'serialization'}

Conclusion

In this article, we learnt to pickle and unpickle in Python 3.x. or earlier using built-in pickle module.