简体   繁体   中英

Storing dictionary with lambda function in python

I have a data structure that looks like this:

x = defaultdict(lambda: defaultdict(list))

Unfortunately I am having problems storing this data structure in pickle format like this:

import pickle
with open('x.pkl', 'wb') as f: pickle.dump(x, f)

There error I get is this:

PicklingError: Can't pickle <function <lambda> at 0x7f20a790e398>: it's not found as file_im_referencing.<lambda>

Is there a better way to write this data to disk?

Pickle cannot work with lambda nor local function now. You can make a GLOBAL function to do that

from collections import defaultdict
import pickle

def _global_helper_function():
    return defaultdict(list)

x = defaultdict(_global_helper_function)
pickle.dump(x, f)

By making a function global, it is associated with file which makes it easier for pickle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM