Dictionary Keys, Values and Items Views
Core idea
d.keys(), d.values() and d.items() return views: objects that reflect the current dictionary. A for loop over d itself visits keys. Use items() with tuple unpacking to visit both key and value. Convert a view to a list when you need a snapshot of its entries.
stock = {"pen": 2, "pad": 3}print(list(stock.keys()))print(list(stock.values()))print(list(stock.items()))Each view exposes a different part of the same entries. list() displays their current contents.
Iterate with unpacking
stock = {"pen": 2, "pad": 3}for label, count in stock.items(): print(label, count)Each item is a pair; the two names receive its key and value.
View versus snapshot
stock = {"pen": 2}keys = stock.keys()snapshot = list(keys)stock["pad"] = 3print(list(keys))print(snapshot)The view reflects the new key; the list of keys does not.
Common mistake
Adding or deleting keys while iterating a live dictionary may raise RuntimeError or skip entries. Collect keys in a list first if you need to change the structure.
Practice
Use values() and an accumulator to total a mapping of three item counts; then print each label and count with items().
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dictionary views
Check your understanding of keys values and items.
What is printed?
print(list({"x": 1, "y": 2}))What is printed?
print(list({"x": 2, "y": 5}.values()))What is printed?
d = {"x": 1}v = d.keys()d["y"] = 2print(list(v))Which approach avoids changing the key structure of a dictionary while iterating its live view?