TypeError: can't pickle dict_items objects
Asked Answered
M

2

15

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

Matriculation answered 12/2, 2019 at 20:14 Comment(0)
H
22

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()))
Hypomania answered 12/2, 2019 at 20:28 Comment(2)
Not a satisfactory answer (my apologies for bothering after 8 yeras:-); it does not explain why it doesn work (regardless of why it worked on PY2), and the workaround would be useless if the dict_items are buried deep in some nested structure.Fossick
after 8 years, really I don't know what you're talking about... dict_items object is not picklable probably because of the security feature that python introduces in dict hashes, that would make pickled data invalid on reload.Mississippian
G
0

If you use the json module it works fine.

i.e

json.dump(arr, open(file, 'r'))
arr = json.load(open(file, 'r'))
God answered 31/8, 2023 at 20:18 Comment(1)
Sorry that was not the question which is super old. If I was coding in python right now I would use JSON over the pickle format. Laters.Oyler

© 2022 - 2024 — McMap. All rights reserved.