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.

countsdictionarynamecurrent keyvalue > 10test the retrieved valuecounts[name]associated countfor loop givesindex lookupcompare
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. 1
    The for statement retrieves a key from the dictionary.
  2. 2
    The index operator retrieves the value associated with that key.
  3. 3
    The if statement compares that value with the filtering condition.
dictionary keycurrent keyvalueretrieved with indexoperatorvalue > 10conditionselected entryif truenext keyif falseretrievetesttruefalse
What happens to each key-value pair when the condition is true versus when it is false?
Code walkthrough
counts = {
    "Alice": 14,
    "Bob": 21,
    "Chuck": 1
}

for name in counts:
    if counts[name] > 10:
        print(name, counts[name])
  1. 1
    The dictionary contains three name-count entries.
  2. 2
    The loop examines each key.
  3. 3
    The index expression counts[name] retrieves the corresponding count.
  4. 4
    Alice and Bob satisfy the condition, so their entries are printed.
  5. 5
    Chuck 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.
Output
Alice 14
Bob 21

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.

Alice: 14Alice: 14selectedBob: 21Bob: 21selectedChuck: 1keep entrykeep entry
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}
Notes on the code
  • 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.
countsoriginal dictionarykey-value paircurrent entryvalue > 10filter conditionfilterednew dictionaryinspecttest valuetrue: add pair
How do selected entries move from the original collection into a separate result collection?
Worked example

Keep Counts Above the Threshold

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

  1. 1
    Start with the source

    Use the dictionary that contains names as keys and counts as values.

  2. 2
    Create the result

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

  3. 3
    Inspect each key

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

  4. 4
    Apply the condition

    When counts[name] is greater than 10, assign that key and value into filtered.

Result

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 like
    if name > 10:
    Why it fails

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

    Do this instead

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

  • Common mistake

    Forgetting the index operator

    What it looks like
    if key == 10:
    Why it fails

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

    Do this instead

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

  • Common mistake

    Using assignment where comparison is required

    What it looks like
    if counts[name] = 10:
    Why it fails

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

    Do this instead

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

  • Common mistake

    Modifying the dictionary being iterated over

    Why it fails

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

    Do this instead

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

Related concepts

More concepts starting with F