Iterating Through Dictionary Keys
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-First Loop
When a dictionary is used directly as the sequence in a for loop, Python gives the loop one key at a time. It does not automatically give the loop the corresponding values. This key-first behavior is the foundation for both ordinary dictionary traversal and filtering dictionary entries by value.
chuck
annie
janThe loop variable key contains the current key, such as chuck or annie. To obtain the associated count, use the current key inside bracket notation: counts[key]. The loop therefore has two separate actions: it receives a key from the dictionary, then uses that key to retrieve the value.
Following a Value Filter
Filtering by value combines three elements. First, the for statement supplies a key. Second, the index operator retrieves the value associated with that key. Third, an if statement tests the retrieved value. Only when the condition is true does the loop body run for that entry.
counts = { "chuck": 1, "annie": 13, "jan": 15 } for key in counts: if counts[key] > 10: print(key, counts[key])
What do you think happens?
Which entries will be printed by the loop, and why?
Reveal answer
Answer: annie and jan
Their values are 13 and 15, which are both greater than 10. Chuck has a value of 1, so that entry does not satisfy the condition.
The Bracket Lookup
The index operator is the bracket notation used to retrieve a dictionary value from a key. During iteration, counts[key] means: use the current key to look up its associated value in counts.
The expression key and the expression counts[key] are not interchangeable. key refers to the dictionary key currently held by the loop variable. counts[key] refers to the value stored under that key. A condition that is meant to test counts must therefore compare counts[key], not key.
| Expression | What it represents | Role in value filtering |
|---|---|---|
| key | The current dictionary key | Identifies which entry is being examined |
| counts[key] | The value associated with the current key | Provides the value for the condition |
| counts[key] > 10 | A comparison involving that value | Determines whether the entry is selected |
Insertion Order and Output
Dictionary keys maintain insertion order. If the dictionary is created with chuck first, annie second, and jan third, a direct for loop visits those keys in that same order. This makes the order of printed output predictable and makes it possible to trace the loop one iteration at a time.
Tracing Both Key and Value
Determine what each iteration holds for the dictionary counts = {"chuck": 1, "annie": 13, "jan": 15}.
First iteration: key holds chuck. Looking up counts[key] retrieves 1.
Second iteration: key holds annie. Looking up counts[key] retrieves 13.
Third iteration: key holds jan. Looking up counts[key] retrieves 15.
Loop completion: After jan, there are no more keys, so the loop ends.
The loop visits chuck, then annie, then jan. A statement that prints both key and counts[key] prints the corresponding key-value pairs in that order.
Keeping the Selected Entries
Printing a passing entry is useful when inspecting a loop. When the selected entries are needed later, assign each passing key-value pair to a new dictionary. The original dictionary is used for the iteration, while filtered stores only the entries that satisfy the condition.
{'annie': 13, 'jan': 15}This is filtering: the loop selects existing entries whose values pass the test. The selected key and its existing value are placed in filtered. The loop does not change those entries while selecting them. A filtered dictionary can later be passed to other functions, iterated again, or modified further.
A list can also be used when the later task needs only the selected keys or another collected representation. The essential filtering step remains the same: iterate through keys, retrieve each value with bracket notation, and keep the entry when the condition is true.
Filtering Versus Changing
| Operation | What the loop does | Typical result |
|---|---|---|
| Filtering | Selects entries whose values satisfy a condition | A printed selection or a new dictionary containing selected entries |
| Transforming | Changes entries or their representation for a later purpose | A modified or differently represented result |
For the pattern in this article, the condition selects entries based on their values. Assigning filtered[key] = counts[key] preserves the selected key and value in a new dictionary. That is different from selecting an entry and then modifying it. Keeping this distinction clear helps you identify whether your loop is choosing existing data or producing changed data.
Mistakes That Break the Filter
Comparing the key instead of the value
The loop variable contains a key. It does not contain the dictionary value that should be tested.
Fix:
Use if counts[key] > 10: so the index operator retrieves the associated value first.Forgetting the index operator
This compares the key directly with 10 rather than testing the value stored under that key.
Fix:
Write the comparison against counts[key].Using assignment where comparison is intended
The condition needs to compare the retrieved value with a threshold.
Fix:
Use a comparison such as counts[key] == 10 or counts[key] > 10.Expecting the loop variable to contain both pieces of the entry
A direct dictionary loop traverses keys. The value must be retrieved separately.
Fix:
Use print(key, counts[key]) when both the key and its corresponding value are needed.Modifying the dictionary being traversed
Changing the dictionary during iteration is identified as a common mistake in this pattern.
Fix:
Collect selected entries in a new dictionary such as filtered, then use that result afterward.
Practice the Trace
Given the dictionary scores = {"red": 4, "blue": 12, "green": 7}, write a for loop that prints the keys and values whose values are greater than 5. Before checking your result, predict the order of the output.
Hints
- A direct loop over scores supplies one key at a time.
- Use scores[key] to retrieve the value for the current key.
- The dictionary was created in the order red, blue, green.
blue 12
green 7Red is examined first but is not printed because its value is 4. Blue is printed next because 12 is greater than 5. Green is printed last because 7 is also greater than 5. The output order follows the dictionary's insertion order, while the condition determines which entries appear.
Key Takeaways
- A for loop over a dictionary traverses its keys.
- Use dictionary[key] to retrieve the value associated with the current key.
- To filter by value, test the retrieved value in an if condition.
- Filtered entries can be printed immediately or collected in a new dictionary.
- Dictionary keys maintain insertion order, so the loop and its output follow that order.
Key Takeaways
- A dictionary used directly in a for loop supplies keys, not values.
- The current key must be used with bracket notation to retrieve its value.
- Filtering selects entries whose values satisfy a condition; it does not by itself transform them.
- Selected entries can be printed or collected into a new dictionary.
- Keys are visited in insertion order, which makes loop output predictable.