Python’s Pickle Module

There are many modules that I use on the regular (thanks to all those contributors) but there is one in particular I want to focus on today. That is Python’s pickle module.

The pickle module is useful for storing data in a serialized fashion. It’s great for storing dictionaries of any type. For example, you can store all the details about some product, like an outfit or a meal, like so:

import pickle

outfit = {‘top’:’pink sparkly shirt’,’bottoms’:’black slacks’,’shoes’:’swanky heels’,’accessories’:’diamond earrings, gold necklace’}

with open(‘C://Users/me/outfits/fancy.txt’,’w’) as pkl:
    pickle.dump(outfit,pkl)

Then say later you decide you want to include an occasion key in this outfit’s dictionary:

with open(‘C://Users/me/outfits/fancy.txt’,’w’) as pkl:
    outfit = pickle.load(pkl)

outfit[‘occasion’] = ‘fancy dinner’

with open(‘C://Users/me/outfits/fancy.txt’,’w’) as pkl:
    pickle.dump(outfit,pkl)

And now you have a file representing an outfit you have put together that you can pull out at any time and reference.

Now for the meal example:

import pickle

recipes = {}

recipes[‘dinner’] = {‘main course’:’pasta’,’appetizer’:’garlic bread’,’side’:’salad’,’drink’:’raspberry lemon drop’}

recipes[‘breakfast’] = {‘main course’:’cereal’,’side’:’fruit’,’drink’:’vanilla latte’}

with open(‘C://Users/me/recipes.txt’,’w’) as pkl:
pickle.dump(recipes,pkl)

And there we have the beginnings of a meal catalog, which includes dictionaries within a dictionary.

Pretty cool!