writing pickle function

Chris Rebert clp2 at rebertia.com
Fri Jan 23 16:38:53 CET 2009

On Fri, Jan 23, 2009 at 6:48 AM,  <perfreem at gmail.com> wrote:
> hello,
> i am using nested defaultdict from collections and i would like to
> write it as a pickle object to a file. when i try:
> from collections import defaultdict
> x = defaultdict(lambda: defaultdict(list))
> and then try to write to a pickle file, it says:
> TypeError: can't pickle function objects
> is there a way around this? it's simply a dictionary that i want to
> write to file.. this works no problems with ordinary dicts.

Functions aren't pickleable because they're Python code (which is
itself not pickleable). defaultdicts contain a reference to a function
(in your case, a function defined using lambda), which they use to
create default values. Thus, this causes defaultdicts to not be

This is easily worked around by pickling a plain dict w/ the contents
of the defaultdict (i.e. dict(x) ) and then doing:

x = defaultdict(lambda: defaultdict(list)) #create empty defaultdict
x.update(pickle.load(the_file)) #shove contents of pickled dict into
the defaultdict


Follow the path of the Iguana...

More information about the Python-list mailing list