How to Save Dictionaries, Lists, Tuples and Other Objects With Pickle
Sometimes you just want to save a dictionary, a list, a string, or anything into a file so you can use it later. This can be easily achieved with the module Pickle.
Warning:
The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source. — Pickle Documentation
What is Pickle
Pickle is a module in Python that can be implemented to serialize or de-serialize a Python object, meaning that it can be used to save an object into a file; Just have in mind that this is not the same as saving a configuration file, there are other data structures that we can use to achieve that task such as JSON, CSV, YAML/TOML, etc.
How to save an dictionary with Pickle
Saving an object with Pickle is really easy, all you need to do is to save the object into a file providing the object and the filename, here’s a quick snippet:
import pickle |
And there you go! You have saved the contents of an object into a file. Just remember to always save the file as binary providing the arguments w (writing) and b (binary)
Loading a dictionary
If you have used JSON before then you can find the syntax to be very familiar. We can load a previously pickled object using the .load() method and providing a filename:
import pickle |
As you can see, our dictionary object was loaded correctly. To double-check this, here’s a script that compares if the contents of a dictionary and a saved pickle are the same:
import pickle |
What kind of data can be Pickled?
According to the official documentation, this is the list of object types that can be pickle/unpickled:
None,True, andFalse- integers, floating point numbers, complex numbers
- strings, bytes, bytearrays
- tuples, lists, sets, and dictionaries containing only picklable objects
- functions defined at the top level of a module (using def, not lambda)
- built-in functions defined at the top level of a module
- classes that are defined at the top level of a module
instances of such classes whose dict or the result of calling getstate() is picklable (see section Pickling Class Instances for * details).
This is a very interesting approach if you need to save an object into a file. Just beware that there’s a lot of data structures out there than can help you to save a configuration file. But if you need to save an object, then this seems the right choice!