Sub topic 5
Iterating with keys(), values() and items()
This chapter assumes you can write for loops and f-strings and that you know how to create, read and change a dictionary. It also assumes you know that tuples unpack into several names. Here you will learn what a dictionary produces when you loop over it, what the three view objects are, and how to use them without surprises.
What a plain for loop gives you
Looping over a dictionary yields its keys, not its values and not its pairs.
scores = {"ana": 90, "ben": 72, "cy": 85}
for name in scores:
print(name, scores[name])This prints each name with its score. It works, but every pass through the loop does an extra lookup with scores[name]. Most of the time there is a clearer way to write it.
The loop is equivalent to for name in scores.keys(). The explicit form says what you mean more plainly, so many people prefer it when a loop mixes keys and values.
The three views
A dictionary has three methods that return views:
keys()returns adict_keysobject.values()returns adict_valuesobject.items()returns adict_itemsobject. Each element is a(key, value)tuple.
scores = {"ana": 90, "ben": 72, "cy": 85}
print(scores.keys()) # dict_keys(['ana', 'ben', 'cy'])
print(scores.values()) # dict_values([90, 72, 85])
print(scores.items()) # dict_items([('ana', 90), ('ben', 72), ('cy', 85)])
print(len(scores.items())) # 3A view is not a list. It does not copy the data. It is a window onto the dictionary that you can loop over, measure with len() and test with in.
Unpacking items()
The most common loop over a dictionary uses items() and unpacks each tuple into two names.
scores = {"ana": 90, "ben": 72}
for name, score in scores.items():
print(f"{name}: {score}")The names name and score are your choice. Pick names that describe the data, because k and v are hard to read in longer loops.
If you only need the values, loop over values(). If you need a position counter as well, wrap items() in enumerate() and use a nested pattern for the unpacking.
scores = {"ana": 90, "ben": 72, "cy": 85}
for position, (name, score) in enumerate(scores.items(), start=1):
print(position, name, score)The parentheses around (name, score) are required. Each item from enumerate() is a pair of a counter and a tuple, so the pattern must match that shape.
For nested dictionaries, loop at each level.
teams = {
"red": {"ana": 90, "ben": 72},
"blue": {"cy": 85},
}
for team, members in teams.items():
for name, score in members.items():
print(team, name, score)Views are live
A view reflects the dictionary as it is now, not as it was when you created the view.
scores = {"ana": 90, "ben": 72}
keys = scores.keys()
scores["cy"] = 85
print(list(keys)) # ['ana', 'ben', 'cy']The keys view saw the new entry because it reads from scores each time. This is useful when a long-lived view should track changes. It is a problem when you want a snapshot. To take one, convert the view to a list.
scores = {"ana": 90, "ben": 72}
snapshot = list(scores.keys())
scores["cy"] = 85
print(snapshot) # ['ana', 'ben']What views do and do not support
Views are iterable, sized and support membership tests. They are not sequences.
scores = {"ana": 90, "ben": 72}
try:
scores.keys()[0]
except TypeError as exc:
print(exc) # 'dict_keys' object is not subscriptable
first_key = next(iter(scores))
print(first_key) # ana
print(list(reversed(scores))) # ['ben', 'ana'] (Python 3.8+)Use next(iter(...)) to read the first element. Use list(...) if you need an index. reversed() works on a dictionary and its views from Python 3.8 onward. The order it reverses is insertion order, which a later chapter covers.
The three views differ in how they handle membership tests and set operations.
| View | Elements | Cost of `x in view` | Set operations |
|---|---|---|---|
| `keys()` | keys | Hash lookup, fast | Yes |
| `values()` | values | Scans every value with `==`, slow | No |
| `items()` | `(key, value)` tuples | Looks up the key, then compares the value | Yes, if all values are hashable |
The cost difference matters. "ana" in scores and "ana" in scores.keys() are both fast. 90 in scores.values() checks values one by one, so it takes time proportional to the dictionary's size.
Set operations on keys() and items()
Keys are unique and hashable, so keys() behaves like a set. The operators &, |, - and ^ and the comparisons <= and >= work on it, and each operator returns a real set. The same is true of items() when every value is hashable.
a = {"x": 1, "y": 2, "z": 3}
b = {"y": 2, "z": 9, "w": 0}
print(sorted(a.keys() & b.keys())) # ['y', 'z'] keys in both
print(a.keys() - b.keys()) # {'x'} keys only in a
print(sorted(a.keys() | b.keys())) # ['w', 'x', 'y', 'z']
print(a.items() & b.items()) # {('y', 2)} identical pairs
print(a.keys() >= {"x", "y"}) # TrueThe result is a set, so its printed order is not guaranteed. The examples use sorted() where the order would otherwise vary between runs.
The intersection of items() shows the pairs that agree in both dictionaries. Here only ("y", 2) matches, because z has different values.
If any value is unhashable, such as a list, a.items() & b.items() raises TypeError, because Python has to put the pairs into a set. A plain membership test such as ("y", 2) in a.items() still works, because it only needs to hash the key.
Gotchas with values()
values() has no set behavior, since values can repeat and need not be hashable. It also has an equality quirk.
d = {"a": 1}
print(d.keys() == d.keys()) # True
print(d.items() == d.items()) # True
print(d.values() == d.values()) # FalseEach call to values() creates a new view object. The dict_values type does not define equality, so Python falls back to identity, and two separate objects are never identical. To compare values, convert them: list(d.values()) == list(e.values()). Use sorted(...) if the order should not matter and the values can be sorted.
Common patterns
Each of these is a short idiom you will meet often.
inventory = {"apple": 3, "pear": 0, "kiwi": 7}
total = sum(inventory.values())
print(total) # 10
in_stock = [name for name, qty in inventory.items() if qty > 0]
print(in_stock) # ['apple', 'kiwi']
best = max(inventory, key=inventory.get)
print(best) # kiwi
best_pair = max(inventory.items(), key=lambda kv: kv[1])
print(best_pair) # ('kiwi', 7)
inverted = {qty: name for name, qty in inventory.items()}
print(inverted) # {3: 'apple', 0: 'pear', 7: 'kiwi'}Each line does one job:
sum(inventory.values())adds the values without building a list.- The list comprehension filters on the value and keeps the key.
max(inventory, key=inventory.get)iterates over keys and ranks each one by its value. It returns a key.max(inventory.items(), ...)returns the whole pair.- The last comprehension swaps keys and values. If two keys share a value, later entries overwrite earlier ones, so the inverted dictionary has fewer entries than the original.
Changing a dictionary while looping
Changing a value for an existing key during iteration is safe, because the dictionary's size does not change.
inventory = {"apple": 3, "pear": 0, "kiwi": 7}
for name in inventory:
inventory[name] *= 2
print(inventory) # {'apple': 6, 'pear': 0, 'kiwi': 14}Adding or removing keys during the loop is different. Python raises RuntimeError: dictionary changed size during iteration. A later chapter covers this in detail. The short rule is to loop over list(d) or list(d.items()) when you need to add or delete entries.
Choosing a view
- Need only the keys: loop over the dictionary, or over
keys()if you want to be explicit. - Need only the values: loop over
values(). - Need both: loop over
items()and unpack. - Need to compare the keys or pairs of two dictionaries: use set operators on
keys()oritems(). - Need a fixed copy, an index, or sorting: convert with
list(...)orsorted(...).
Exercise
Given a = {"x": 1, "y": 2} and b = {"y": 2, "z": 3}, write an expression that gives the set of keys that appear in exactly one of the two dictionaries. What does it return?
Show answer
a.keys() ^ b.keys(). The ^ operator on keys views returns the symmetric difference, which is {'x', 'z'} here. Only x is unique to a and only z is unique to b. The key y appears in both, so it is left out. The printed order of the set is not guaranteed.
Exercise
What does this code print, and why? d = {"a": 1, "b": 2} v = d.values() d["c"] = 3 print(len(v), 3 in v, d.values() == d.values())
Show answer
It prints 3 True False. The values() view is live, so after d["c"] = 3 it has three elements and 3 in v is true. The last comparison is false because each values() call creates a new view object, and dict_values compares by identity rather than by contents.
Exercise
Write a loop that prints each key and value of scores = {"ana": 90, "ben": 72, "cy": 85} on its own line as 1. ana = 90, with a counter that starts at 1.
Show answer
for position, (name, score) in enumerate(scores.items(), start=1):
print(f"{position}. {name} = {score}")
The parentheses around (name, score) are needed because enumerate() yields a counter paired with each (key, value) tuple.