< Prev  |  Home  |  Next >

Python Pickling

This section is just a quick note on how to load/save complex data structures to/from a file. When we wanted to load/save strings, we just wrote/read directly to the file. But what about with, say, a dictionary to store a phonebook like this:

This is a complex structure: it’s a dictionary containing 2 keys (the names), linking to other dictionaries containing 2 keys for home and work phone numbers. Dictionaries within dictionaries. To store this dictionary in a file, we’d have to loop through all of the names, and then loop through all of the phone numbers, and find some clever way of saving it all in one file.

Thankfully, we can just use the pickle module to load and save the dictionary automatically. Here’s a quick example from the python wiki:

We can do this with variables of any type: strings, lists and dictionaries. When dealing with the file, “wb” and “rb” mean read/write in binary mode. This means that we’re dealing with a stream of binary data rather than ASCII or Unicode text.

< Prev  |  Home  |  Next >