Dictionaries

Object views and iterating over dictionaries

In this Python lesson, you'll explore object views, dynamic representations of a dictionary's keys, values, or items, and learn how to use them to iterate over dictionaries.


Let's create a new dictionary that we can work with:

Python

Sometimes, you'll need to extract the keys from a dictionary.

You can do so using the dict.keys() method.

Python
Output

The dict.keys() method returns a so-called view object.

This view object provides a dynamic view of the dictionary's keys.

It's dynamic because it reflects changes made to the dictionary in real-time.

Here we add a new key after creating the view object.

Python
Output

Notice that the new key has been added to the view object.

You can transform the view object into a static list using the list() function:

Python
Output

If you want to extract a dictionary's values instead of its keys, you can use the dict.values() method:

Python
Output

Another view object method is dict.items(), which returns a dynamic view of all key-value pairs in a dictionary:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

Sometimes it's necessary to iterate over keys, values or key-value pairs in dictionaries.

We can accomplish this using a for-loop and the view objects introduced earlier.

Here, we iterate over the values of our dictionary:

Python
Output

We don't need to use a view object to iterate over the keys of our dictionary:

Python
Output

With dict.items() we can iterate over keys and values simultaneously:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python