类型错误:不能腌制 dict_items 对象

fue*_*zig 12 serialization python-2.x python-3.x dill

为什么

pickle.dumps({}.items())
Run Code Online (Sandbox Code Playgroud)

TypeError: can't pickle dict_items objects在 Python 3.5.2 中失败,但在 Python 2.7.12 中没有?

“腌制”字典

pickle.dumps({})
Run Code Online (Sandbox Code Playgroud)

适用于两个 Python 版本(并且在 Python 2.7.12 中提供与上述命令相同的输出)。

Jea*_*bre 18

because in python 2.7 .items() returns a mere list of tuples, which is picklable.

In python 3.x it returns a dict_items object (that doesn't exist in python 2), not picklable (but faster since it doesn't generate a list, it's the rough equivalent of python 2.x iteritems()).

But you can force list conversion to simulate python 2.x behaviour:

pickle.dumps(list(d.items()))
Run Code Online (Sandbox Code Playgroud)

  • 不是一个令人满意的答案(我很抱歉在 8 年后打扰:-);它没有解释为什么它不起作用(无论它为什么在 PY2 上起作用),并且如果“dict_items”深埋在某些嵌套结构中,那么解决方法将毫无用处。 (4认同)
  • 8年后,我真的不知道你在说什么...`dict_items`对象不可picklable,可能是因为python在dict哈希中引入的安全功能,这会使pickled数据在重新加载时无效。 (2认同)