Why does
pickle.dumps({}.items())
fail with TypeError: can't pickle dict_items objects
in Python 3.5.2 but not in Python 2.7.12?
"Pickling" the dictionary with
pickle.dumps({})
works in both Python versions (and in Python 2.7.12 gives the same output as the command above).
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()))