Accessing Dictionary Values with the Index Operator
The loop variable is a key. The expression counts[key] is what moves from that key to the value stored under it.
The Key-to-Value Puzzle
Suppose a dictionary records how many times each name appears. You want to select only the names whose counts are greater than 10. The condition is about the values, but a for loop over a dictionary gives you the keys. The solution is to use each key with the index operator, retrieve its associated value, and then test that value.
The loop variable is a key. The expression counts[key] is what moves from that key to the value stored under it.
Tracing One Dictionary Entry
For every key, the filtering pattern has three stages. First, the for statement retrieves a key. Second, the index operator retrieves the value associated with that key. Third, an if statement compares the retrieved value with a condition. If the comparison is true, the loop body runs. If it is false, the loop moves to the next key.
counts = {
"Ada": 14,
"Ben": 11,
"Chuck": 1
}
for name in counts:
if counts[name] > 10:
print(name, counts[name])- 1The dictionary stores names as keys and counts as values.
- 2The loop places one key at a time into name.
- 3counts[name] retrieves the count belonging to that name.
- 4The if statement keeps the entry only when that count is greater than 10.
- 5The print statement runs for entries that satisfy the condition.
Ada 14
Ben 11Selecting Rather Than Changing
Filtering means selecting the entries that satisfy a condition. In this pattern, the original key-value entries are selected because their values meet the test. The loop does not need to change the values in order to filter them. Transforming would be a different operation: it would modify entries before producing a result. Keep the two questions separate: which entries should be included, and what should happen to an included entry?
A value-based filter answers whether an entry belongs in the result. It does not require changing the entry that passes.
Building a Filtered Result
Printing a matching entry is useful when you only need to inspect the result. When the result will be used later, create a new dictionary and assign each matching key-value pair to it. After the loop, the new dictionary contains only entries whose values exceeded the threshold.
{'Ada': 14, 'Ben': 11}The assignment filtered[name] = counts[name] preserves both parts of the matching entry: the key is stored under name, and the value is retrieved with counts[name]. The resulting dictionary can be passed to other functions, iterated again, or modified further.
Common Filtering Mistakes
Common mistake Comparing the key instead of the value
What it looks likeif name > 10:Why it failsThe loop variable name contains a key, not the count stored under that key. A key may be a string, so comparing it with the number 10 does not test the dictionary value.
Do this insteadRetrieve the value first: if counts[name] > 10:
Common mistake Forgetting the index operator
What it looks likeif name == 10:Why it failsThis compares the key directly with 10. It does not access the value associated with the key.
Do this insteadUse the key inside the index operation: if counts[name] == 10:
Common mistake Using assignment instead of comparison
What it looks likeif counts[name] = 10:Why it failsThe filtering condition needs a comparison. Assignment with = is not the comparison operation used to test whether a value equals 10.
Do this insteadUse == when testing equality: if counts[name] == 10:Common mistake Modifying the dictionary being iterated through
What it looks likeAdding or removing entries from counts while the for loop is processing counts.
Why it failsThe source material identifies modifying the dictionary during iteration as a common mistake.
Do this insteadCollect matching entries in a new dictionary such as filtered, then use that result after the loop.
Practice the Pattern
Write a loop that examines the dictionary scores and collects into a new dictionary only the entries whose values are at least 80. Do not change the selected values.
Hints
- The loop variable will contain a key.
- Use scores[key] to retrieve the value for the condition.
- Assign the matching key-value pair to a separate dictionary.
What do you think happens?
Which expression should replace the condition if the loop variable is key and the dictionary is scores?
Reveal answer
scores[key] >= 80
The loop variable is a key, so scores[key] retrieves the value associated with that key. The comparison then tests the value against 80.
Pattern Summary
- 1A for loop over a dictionary gives you keys, not values.
- 2Use the index operator, such as counts[key], to retrieve the value associated with the current key.
- 3Place the retrieved value in a condition to select entries by their values.
- 4Filtering selects matching entries; it does not require modifying them.
- 5Print matching entries immediately or assign them to a new dictionary for later use.
At a glance
- A dictionary loop supplies keys, so value-based filtering requires a lookup such as counts[key].
- The index operator connects the current key to the value that the condition must test.
- A filter selects existing entries, while a transformation changes entries.
- Matching entries can be printed or collected in a new dictionary for later use.