不能腌制defaultdict [英] Can't pickle defaultdict
问题描述
我有一个类似下面的defaultdict:
I have a defaultdict that looks like this:
dict1 = defaultdict(lambda: defaultdict(int))
问题是,我不能使用cPickle腌制它.我在这里找到的解决方案之一是使用模块级函数而不是lambda.我的问题是,什么是模块级功能?如何在cPickle中使用字典?
The problem is, I can't pickle it using cPickle. One of the solution that I found here is to use module-level function instead of a lambda. My question is, what is module-level function? How can I use the dictionary with cPickle?
推荐答案
模块级函数是在模块级定义的函数,这意味着它不是类的实例方法,它不嵌套在另一个函数中,并且它是一个带有名称而不是名称的真实"函数一个lambda函数.
A module-level function is a function which is defined at module level, that means it is not an instance method of a class, it's not nested within another function, and it is a "real" function with a name, not a lambda function.
因此,要腌制defaultdict
,请使用模块级函数而不是lambda函数来创建它:
So, to pickle your defaultdict
, create it with module-level function instead of a lambda function:
def dd():
return defaultdict(int)
dict1 = defaultdict(dd) # dd is a module-level function
比你可以腌的
tmp = pickle.dumps(dict1) # no exception
new = pickle.loads(tmp)
这篇关于不能腌制defaultdict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!