How can I use pickle to save a dict (or any other Python object)?

I have looked through the information that the Python docs give, but I’m still a little confused. Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it?

1Best Answer
11

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.

Leave a Comment