Dictionary Views in Python

First published:

Last Edited:

Number of edits:

In Python, dictionary views actually change their data if the underlying dictionary changes. Let's remove some keys:

>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> keys = data.keys()
>>> keys
dict_keys(['a', 'b', 'c'])
>>> del data['a']
>>> keys
dict_keys(['b', 'c'])

It also works for the items:

>>> items = data.items()
>>> items
dict_items([('b', 2), ('c', 4)])
>>> items_list = list(items)
>>> items_list
[('b', 2), ('c', 4)]
>>> data['c'] = 0
>>> items
dict_items([('b', 2), ('c', 0)])
>>> items_list
[('b', 2), ('c', 4)]

Note that once the dict_items object is cast into a list, it loses the reference to the data item.

And, just out of curiosity and, as expected, it is not serializable:

>>> with open('test.dat', 'w') as f:
...  pickle.dump(items, f)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: cannot pickle 'dict_items' object


These are the other notes that link to this one.

Nothing links here, how did you reach this page then?


Share your thoughts on this note
Aquiles Carattino
Aquiles Carattino
This note you are reading is part of my digital garden. Follow the links to learn more, and remember that these notes evolve over time. After all, this website is not a blog.
© 2021 Aquiles Carattino
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License
Privacy Policy