Filtering Lists by Condition
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 Filtering Puzzle
Suppose a dictionary records how many times each name appears in a dataset. You want only the names whose counts are greater than 10. The key challenge is that a for loop over a dictionary gives you keys. To test a value, you must first use the current key with the index operator, such as counts[key], to retrieve that key's value.
Three Steps in Every Check
- 1The for statement retrieves a key from the dictionary.
- 2The index operator retrieves the value associated with that key.
- 3The if statement compares that value with the filtering condition.
counts = {
"Alice": 14,
"Bob": 21,
"Chuck": 1
}
for name in counts:
if counts[name] > 10:
print(name, counts[name])- 1The dictionary contains three name-count entries.
- 2The loop examines each key.
- 3The index expression counts[name] retrieves the corresponding count.
- 4Alice and Bob satisfy the condition, so their entries are printed.
- 5Chuck has a count of 1, so the condition is false and that entry is not printed.
- The for loop places one key at a time in name.
- counts[name] retrieves the count belonging to that key.
- Only values greater than 10 reach the print statement.
Alice 14
Bob 21What do you think happens?
Which entries will be printed by the loop, and why?
Reveal answer
Alice and Bob, because their values are greater than 10
The condition tests counts[name], not the name itself. Alice has 14 and Bob has 21; Chuck has 1 and is excluded.
Selecting Without Changing
Filtering means selecting the entries that satisfy a condition. The selected entries keep their existing keys and values. The loop may print those entries immediately, or it may place them into another collection for later use. Transforming is a different operation: it changes entries or prepares modified results. A filtering loop should therefore be read as a selection step, not as a value-changing step.
Building a Result Collection
Printing is useful when you only need to inspect the matches. When the matches must be used later, create a separate result collection. A new dictionary can receive the original key and its original value whenever the condition is true.
{'Alice': 14, 'Bob': 21}- filtered starts as a new empty dictionary.
- The key-value pair is added only when the value is greater than 10.
- The original counts dictionary is used as the source of the filtering.
Keep Counts Above the Threshold
Select every name whose count is greater than 10 and store the selected entries in a new dictionary.
- 1Start with the source
Use the dictionary that contains names as keys and counts as values.
- 2Create the result
Create an empty dictionary named filtered so the matching entries have somewhere to go.
- 3Inspect each key
The loop variable contains a name, so use counts[name] to retrieve that name's count.
- 4Apply the condition
When counts[name] is greater than 10, assign that key and value into filtered.
filtered contains only the entries whose values exceed 10: Alice with 14 and Bob with 21.
The same selection idea can also be used when the desired result is a list, such as a list of keys that pass the value test. The essential pattern remains unchanged: iterate over keys, retrieve each value with the index operator, test the value, and add only matching results to the separate collection.
Mistakes Beginners Make
Common mistake Comparing the key instead of the value
What it looks likeif name > 10:Why it failsThe loop variable contains a key. It does not contain the dictionary value being filtered.
Do this insteadRetrieve the value first: if counts[name] > 10:
Common mistake Forgetting the index operator
What it looks likeif key == 10:Why it failsThe comparison tests the key directly rather than the value associated with that key.
Do this insteadUse the key inside the dictionary lookup: if counts[key] == 10:
Common mistake Using assignment where comparison is required
What it looks likeif counts[name] = 10:Why it failsThe condition needs to compare a retrieved value with a threshold.
Do this insteadUse a comparison operator such as ==, >, or another appropriate comparison.
Common mistake Modifying the dictionary being iterated over
Why it failsThe filtering pattern is intended to select entries into a separate result collection.
Do this insteadBuild a new dictionary, such as filtered, instead of modifying the source dictionary during iteration.
Practice the Pattern
Write a loop that examines a dictionary named scores and creates a new dictionary named passing. Add an entry to passing only when its value is greater than 50. Make sure the loop variable is treated as a key and that the value is retrieved with the index operator.
Hints
- Begin with passing = {}.
- Loop over the keys in scores.
- Use scores[key] in the condition.
- Assign passing[key] = scores[key] only when the condition is true.
What do you think happens?
If a value does not satisfy the condition, what should happen to that entry in the result dictionary?
Reveal answer
It should be left out of the result dictionary
Filtering selects entries whose values satisfy the condition. Entries that fail the condition are skipped.
Pattern to Remember
- 1A for loop over a dictionary gives you keys.
- 2Use the index operator, such as counts[key], to retrieve the value connected to the current key.
- 3Test the retrieved value with a condition; the loop body runs only for entries that pass.
- 4Filtering selects entries without requiring their values to change.
- 5Print matches immediately or collect them in a new dictionary or list for later use.
Key Takeaways
- Dictionary iteration supplies keys, not values.
- The index operator retrieves the value that a filtering condition must test.
- A filtering loop selects matching entries; it does not automatically transform them.
- Matching entries can be printed or collected into a separate dictionary or list.
- The safest pattern is to iterate over the source dictionary and build a separate result collection.