Dictionary Views and Iteration
One of the most common tasks you’ll perform with a dictionary is iterating over its contents. Python provides efficient and elegant ways to do this using dictionary views. A view is a special object that provides a dynamic “window” into the dictionary’s keys, values, or items, without making a separate copy of the data.
Understanding Dictionary Views: .keys()
, .values()
, and .items()
my_dict.keys()
: Returns a view object displaying a list of all the keys.my_dict.values()
: Returns a view object displaying a list of all the values.my_dict.items()
: Returns a view object displaying a list of all(key, value)
tuple pairs.
Pyground
Create a dictionary and display its keys, values, and items views.
Expected Output:
Keys view: dict_keys(['title', 'year', 'rating']) Values view: dict_values(['Arrival', 2016, 8.0]) Items view: dict_items([('title', 'Arrival'), ('year', 2016), ('rating', 8.0)])
Output:
Views are Dynamic and “Live”
A key feature of views is that they are connected to the original dictionary. If the dictionary changes, the view reflects that change instantly.
Pyground
Create a keys view, then add a new key to the dictionary and observe the view.
Expected Output:
Initial view: dict_keys(['title', 'year']) Updated view: dict_keys(['title', 'year', 'director'])
Output:
If you need a static “snapshot” of the keys at a certain point in time, you can convert the view to a list: key_list = list(movie.keys())
.
Common Iteration Patterns
There are several ways to loop over a dictionary. Choosing the right one depends on whether you need the keys, the values, or both.
Iterating over Keys (The Default)
Looping directly over a dictionary yields its keys. This is the most common and straightforward iteration method.
Pyground
Iterate over a dictionary's keys and print each key.
Expected Output:
Student scores: - Asha: 91 - Kabir: 86 - Mira: 95
Output:
Advanced Iteration and Transformation
Filtering a Dictionary
A common task is to create a new dictionary that is a subset of an existing one, based on some condition. A dictionary comprehension is the perfect tool for this.
Pyground
From a dictionary of student scores, create a new dictionary containing only the students who passed (score >= 90).
Expected Output:
{'Asha': 91, 'Mira': 95}
Output:
Set Operations on Views (Python 3.9+)
Dictionary key views behave like sets, meaning you can perform set operations like intersection (&
), union (|
), and difference (-
) on them. This is useful for comparing the keys of two dictionaries.
Pyground
Find which configuration settings are common to both a default and a user config dictionary.
Expected Output:
Common settings: {'font_size', 'theme'} All possible settings: {'show_welcome', 'font_size', 'username', 'theme'}