![]() |
VOOZH | about |
Pickling is the process of converting a Python object (such as a list, dictionary, or class object) into a byte stream so that it can be saved to a file or transmitted over a network.
In the below example, a Python dictionary is saved (pickled) to a file and then loaded (unpickled) back, printing the original dictionary.
{'name': 'Jenny', 'age': 25}
Explanation:
Object Serialization converts a Python object into a byte stream for storage or transmission, and deserialization restores it back. In Python, both are done using the pickle module.
In this image, a Python object is converted into a byte stream during serialization, which can be stored in a file, database, or memory. Later, the byte stream is converted back into the original object during deserialization.
In this example, we will serialize the dictionary data and store it in a byte stream. Then this data is deserialized using pickle.loads() function back into the original Python object.
{'Leo': {'key': 'Leo', 'name': 'Leo Johnson', 'age': 21, 'pay': 40000}, 'Harry': {'key': 'Harry', 'name': 'Harry Jenner', 'age': 50, 'pay': 50000}}
Explanation:
In this example, we will use a pickle file to first write the data in it using the pickle.dump() function. Then using the pickle.load() function, we will load the pickle file in Python script and print its data in the form of a Python dictionary.
Leo => {'key': 'Leo', 'name': 'Leo Johnson', 'age': 21, 'pay': 40000}
Harry => {'key': 'Harry', 'name': 'Harry Jenner', 'age': 50, 'pay': 50000}
Explanation: