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

Question

Asked By – Chachmu

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?

Now we will see solution for issue: How can I use pickle to save a dict (or any other Python object)?


Answer

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.

This question is answered By – Blender

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0