On Fri, Jan 23, 2009 at 6:48 AM, <perfr...@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 pickleable. 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 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list