DEV Community

Christian Barra
Christian Barra

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

6 3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started