DEV Community

Christian Barra
Christian Barra

Posted on • Edited on • Originally published at christianbarra.com

Python dictionary views

Dictionary is one of the Python's greatest features and using the keys(), items() and values() methods is really common.

first_dictionary = {"a": 1, "b": 2}
for key, value in first_dictionary.items():
    print(f"Key {key} with value {value}")

# Key a with value 1
# Key b with value 2

But do you know which kind of object is returned?

They all return a special object, called view.

Why are views useful?

  • they provide a dynamic view on the underline object (you change the dictionary and the view will change as well)
  • the object returned by keys() and items() behaves like a set-like object (with items() when the pairs are hashable)

And being a set-like object means you can use the set operations.

Let's consider an example, where we want to find the common keys between 2 dictionaries.

first_dictionary = {"a": 1, "b": 2}
second_dictionary = {"b": 2, "c": 3}

first_dictionary.keys() & second_dictionary.keys()
# {'b'}

& is the intersection operator and returns the common elements between our dictionaries' keys in this case.

What about the elements that are not in common?

first_dictionary = {"a": 1, "b": 2}
second_dictionary = {"b": 2, "c": 3}

first_dictionary.keys() ^ second_dictionary.keys()
# {'a', 'c'}

This is called simmetric difference.

One thing that you cannot do is change the dictionary while iterating over the view object.

for key, value in first_dictionary.items():
    del first_dictionary[key]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

Top comments (0)