Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: can't pickle dict_items objects

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

like image 982
fuenfundachtzig Avatar asked Feb 12 '19 20:02

fuenfundachtzig


1 Answers

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()))
like image 131
Jean-François Fabre Avatar answered Nov 05 '22 17:11

Jean-François Fabre