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:
Sometimes, you'll need to extract the keys from a dictionary.
You can do so using the dict.keys()
method.
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.
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:
If you want to extract a dictionary's values instead of its keys, you can use the dict.values()
method:
Another view object method is dict.items()
, which returns a dynamic view of all key-value pairs in a dictionary:
What will be the output?
What will be the output?
What will be the output?
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:
We don't need to use a view object to iterate over the keys of our dictionary:
With dict.items()
we can iterate over keys and values simultaneously:
What will be the output?
What will be the output?
What will be the output?