Sub topic 5
Iterating with keys(), values() and items()
This chapter assumes you know basic Python syntax, for loops, f-strings, and the difference between mutable and immutable objects. It also assumes you can create a dictionary and read values from it, as covered in earlier chapters.
What a dictionary view is
A dictionary has three methods for looking at its contents: keys(), values() and items(). Each returns a view object. A view is a lightweight window onto the dictionary. It does not copy the data.
| Method | Each element is | Example element |
|---|---|---|
| `keys()` | a key | `"ana"` |
| `values()` | a value | `90` |
| `items()` | a `(key, value)` tuple | `("ana", 90)` |
Looping over a dictionary directly gives you its keys, so for k in d is the same as for k in d.keys().
Looping over items
The most common pattern is to unpack each pair into two names.
scores = {"ana": 90, "ben": 72}
for name, score in scores.items():
print(f"{name}: {score}")
keys = scores.keys()
scores["cy"] = 85
print(list(keys)) # ['ana', 'ben', 'cy']The second half of this example shows that a view is live. We created keys before adding "cy", yet the view includes it. A list made with list(scores) would be a snapshot and would not change.
Looping over keys or values only
Use keys() when you need only the keys and values() when you need only the values. Use items() when you need both. Avoid the slower pattern of looping over keys and then indexing for each one.
scores = {"ana": 90, "ben": 72, "cy": 85}
total = 0
for value in scores.values():
total += value
print(total) # 247
for name in scores:
print(name, end=" ") # ana ben cy
print()
# Works, but does an extra lookup on every pass
for name in scores:
print(name, scores[name], end="; ")
print()The built-in functions sum(), max() and min() accept views directly, so the first loop can be written as sum(scores.values()).
What views support
Views behave like read-only collections. They support len(), iteration and the in operator.
scores = {"ana": 90, "ben": 72}
print(len(scores.keys())) # 2
print("ana" in scores.keys()) # True
print(72 in scores.values()) # True
print(("ben", 72) in scores.items()) # TrueTwo details matter here.
inonkeys()is a hash lookup and is fast. It is the same as"ana" in scores.inonvalues()scans every value, so it takes time proportional to the dictionary's size.
Views of keys and items also behave like sets, so you can compare them with set operators.
a = {"x": 1, "y": 2, "z": 3}
b = {"y": 2, "z": 0, "w": 4}
print(a.keys() & b.keys()) # {'y', 'z'} (set order may vary)
print(a.keys() - b.keys()) # {'x'}
print(a.items() & b.items()) # {('y', 2)}A values() view does not support these operators, because values need not be hashable or unique.
Views are not lists
A view cannot be indexed or sliced. This is a common error for people who learned Python 2 habits or who expect a list.
scores = {"ana": 90, "ben": 72}
try:
scores.keys()[0]
except TypeError as exc:
print(exc) # 'dict_keys' object is not subscriptable
first = list(scores.keys())[0]
print(first) # ana
print(next(iter(scores))) # ana, without building a listConvert to a list when you need indexing. Use next(iter(...)) when you need only the first element.
Order of iteration
Iteration follows insertion order, so keys come out in the order they were first added. Updating an existing key does not move it. The next chapter covers this guarantee in detail.
Changing the dictionary while looping
Because views are live, adding or removing keys during a loop changes the view that the loop is reading. Python detects a change in size and raises RuntimeError. Changing the value of an existing key is allowed, since the size stays the same.
prices = {"apple": 1.0, "pear": 2.0}
for fruit, price in prices.items():
prices[fruit] = price * 2 # allowed: no keys added or removed
print(prices) # {'apple': 2.0, 'pear': 4.0}
try:
for fruit in prices:
prices["kiwi"] = 3.0 # adds a key mid-loop
except RuntimeError as exc:
print(exc) # dictionary changed size during iterationIf you need to add or remove keys, loop over list(prices) instead. A later chapter covers this pitfall in full.
How the views relate
Exercises
Exercise
You build v = d.values(), then run d["new"] = 1. Does v include the new value? Why?
Show answer
Yes. A view is a live window onto the dictionary, not a copy, so it reflects later additions. Use list(d.values()) if you need a snapshot that stays fixed.
Exercise
Write a loop that prints only the names in scores = {"ana": 90, "ben": 72, "cy": 85} whose score is at least 80, without indexing scores inside the loop.
Show answer
for name, score in scores.items(): if score >= 80: print(name) This prints ana and cy. Unpacking the pairs from items() avoids a second lookup.
Exercise
Why does 72 in scores.values() take longer on a large dictionary than "ana" in scores.keys()?
Show answer
Key membership uses a hash lookup and takes roughly constant time. Value membership has no hash index, so Python compares against the values one by one, which takes time proportional to the dictionary's size.