Compress a dictionary and store it to a file in Python

Опубликовано: 02 Октябрь 2024
на канале: Improve Your Programming skills
458
4

You have a fruit store and need to manage it. Assume that your data is big. You need to compress it and save it to the file After that, you can reload its data to memory. This help you save the disk space and protect your data (data is encoded)

I create an Fruit class to store the fruit info. It includes : name of fruit, quantity and its price. I store it into the dictionary as below:
data = {0:Fruit('Apple', 10, 2.4),
1:Fruit('Mango', 135, 1.2),
2:Fruit('Orange', 410, 3.4),
3:Fruit('Banana', 515, 1.1),
4:Fruit('Tomato', 896, 1.2)}

We use io and pickle module for pickling of the object into the memory buffer then compress/decompress the buffer using zlib module