How can I use pickle to save a dict (or any other Python object)?
dictionary, pickle, python
Solution
Try this:
import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open('filename.pickle', 'rb') as handle:
b = pickle.load(handle)
print(a == b)
There's nothing about the above solution that is specific to a `dict` object. This same approach will will work for many Python objects, including instances of arbitrary classes and arbitrarily complex nestings of data structures. For example, replacing the second line with these lines:
import datetime
today = datetime.datetime.now()
a = [{'hello': 'world'}, 1, 2.3333, 4, True, "x",
("y", [[["z"], "y"], "x"]), {'today', today}]
will produce a result of `True` as well.
Some objects can't be pickled due to their very nature. For example, it doesn't make sense to pickle a structure containing a handle to an open file.
Problem
I have looked through the information that the Python documentation for pickle gives, but I'm still a little confused. What would be some sample code that would write a new file and then use pickle to dump a dictionary into it?
Related problems
- How do I write JSON data to a file?
- What is the difference between YAML and JSON?
- How can I parse a YAML file in Python
- How to parse XML and get instances of a particular node attribute?
- How to read HDF5 files in Python
- Creating a simple XML file using python
- How do I read and write CSV files?
- How do I read and write with msgpack?