Concepts / Filtering Lists by Condition

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.

  • Programming

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.

for loop givesindex lookupcomparecountsdictionarynamecurrent keyvalue > 10test the retrieved valuecounts[name]associated count
How does each dictionary key connect to its value, and how does the index operator retrieve the value that the condition tests?

Three Steps in Every Check

  1. The for statement retrieves a key from the dictionary.
  2. The index operator retrieves the value associated with that key.
  3. The if statement compares that value with the filtering condition.
retrievetesttruefalsedictionary keycurrent keyvalueretrieved with indexoperatorvalue > 10conditionselected entryif truenext keyif false
What happens to each key-value pair when the condition is true versus when it is false?

counts = { "Alice": 14, "Bob": 21, "Chuck": 1 } for name in counts: if counts[name] > 10: print(name, counts[name])

What do you think happens?

Which entries will be printed by the loop, and why?

  • Alice and Bob, because their values are greater than 10
  • Chuck only, because it is checked last
  • All three names, because the loop visits every key
Reveal answer

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.

keep entrykeep entryAlice: 14Alice: 14selectedBob: 21Bob: 21selectedChuck: 1
What stays unchanged when entries are filtered, and what changes when entries are transformed?

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.

python
Output (expected)
{'Alice': 14, 'Bob': 21}
inspecttest valuetrue: add paircountsoriginal dictionarykey-value paircurrent entryvalue > 10filter conditionfilterednew dictionary
How do selected entries move from the original collection into a separate result collection?

Keep Counts Above the Threshold

Select every name whose count is greater than 10 and store the selected entries in a new dictionary.

Start with the source: Use the dictionary that contains names as keys and counts as values.

Create the result: Create an empty dictionary named filtered so the matching entries have somewhere to go.

Inspect each key: The loop variable contains a name, so use counts[name] to retrieve that name's count.

Apply 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

  • Comparing the key instead of the value

    The loop variable contains a key. It does not contain the dictionary value being filtered.

    Fix: Retrieve the value first: if counts[name] > 10:

  • Forgetting the index operator

    The comparison tests the key directly rather than the value associated with that key.

    Fix: Use the key inside the dictionary lookup: if counts[key] == 10:

  • Using assignment where comparison is required

    The condition needs to compare a retrieved value with a threshold.

    Fix: Use a comparison operator such as ==, >, or another appropriate comparison.

  • Modifying the dictionary being iterated over

    The filtering pattern is intended to select entries into a separate result collection.

    Fix: Build a new dictionary, such as filtered, instead of modifying the source dictionary during iteration.

Practice the Pattern

EASY

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?

  • It should be added anyway because every key is visited
  • It should be left out of the result dictionary
  • Its value should automatically be changed
Reveal answer

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

  1. A for loop over a dictionary gives you keys.
  2. Use the index operator, such as counts[key], to retrieve the value connected to the current key.
  3. Test the retrieved value with a condition; the loop body runs only for entries that pass.
  4. Filtering selects entries without requiring their values to change.
  5. Print 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.