Friday, August 11, 2017

Python pickle

In this post i am going to talk about pickle. It 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 “serialises” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.

Example of pickle creation

##Import pickle module
import pickle
##Let's create example dic object
eample_dict = {'Sarbadal': ['Manager', '5 years', 'Data Science', 'Photography'], 
               'AJ':       ['Lead', '4 years', 'Data Science', 'Video Game'], 
               'Shobhit':  ['Sr. Analyst', '1 year', 'Data Science', 'Python'], 
               'Abhishek': ['Analyst', '2 years', 'Data Science', 'Painting']}
##Creating pickle
filename = r'F:\Python\Pickle Objects\pickle_example_dict'
file = open(filename, 'wb')
pickle.dump(eample_dict, file)
##Loading pickle
file = open(filename, 'rb')
new_dict = pickle.load(file)

##Checking the loaded object
print(type(new_dict))
print(new_dict['AJ'])

['Lead', '4 years', 'Data Science', 'Video Game']

No comments:

Post a Comment