TypeError: can't pickle dict_items objects

fuenfundachtzig picture fuenfundachtzig · Feb 12, 2019 · Viewed 12.3k times · Source

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).

Answer

Jean-François Fabre picture Jean-François Fabre · Feb 12, 2019

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()))