Accessing Dictionary Values with the Index Operator
A for loop over a dictionary iterates through keys; to filter by value, use the index operator to retrieve each value and test it against a condition.
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])
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
Comparing the key instead of the value
The 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.
Fix:
Retrieve the value first: if counts[name] > 10:Forgetting the index operator
This compares the key directly with 10. It does not access the value associated with the key.
Fix:
Use the key inside the index operation: if counts[name] == 10:Using assignment instead of comparison
The filtering condition needs a comparison. Assignment with = is not the comparison operation used to test whether a value equals 10.
Fix:
Use == when testing equality: if counts[name] == 10:Modifying the dictionary being iterated through
The source material identifies modifying the dictionary during iteration as a common mistake.
Fix:
Collect 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
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
- A for loop over a dictionary gives you keys, not values.
- Use the index operator, such as counts[key], to retrieve the value associated with the current key.
- Place the retrieved value in a condition to select entries by their values.
- Filtering selects matching entries; it does not require modifying them.
- Print matching entries immediately or assign them to a new dictionary for later use.
Key Takeaways
- 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.