Concepts / Accessing Dictionary Values with the Index Operator

Accessing Dictionary Values with the Index Operator

The loop variable is a key. The expression counts[key] is what moves from that key to the value stored under it.

  • Programming

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.

countsname-count entriesAdakey14valueChuckkey1valueloop givescounts[key]next keycounts[key]
What does the loop variable contain at each step, and how does that differ from the value stored under that key?
Key point

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.

Code walkthrough
counts = {
    "Ada": 14,
    "Ben": 11,
    "Chuck": 1
}

for name in counts:
    if counts[name] > 10:
        print(name, counts[name])
  1. 1
    The dictionary stores names as keys and counts as values.
  2. 2
    The loop places one key at a time into name.
  3. 3
    counts[name] retrieves the count belonging to that name.
  4. 4
    The if statement keeps the entry only when that count is greater than 10.
  5. 5
    The print statement runs for entries that satisfy the condition.
nameAdacounts[name]index lookup14value14 > 10conditionAdaselected entryuse keyretrievestest valuetrue
How does the loop move from a key to the corresponding value when checking whether an entry matches a condition?
Output
Ada 14
Ben 11

Selecting 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?

Ada: 14existing entryAda: 14selected unchangedAda: 14existing entryAda: 28modified entrypasses conditionchanges value
Does the code select existing entries unchanged, or does it modify the entries before producing the result?
Key point

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.

python
Output
{'Ada': 14, 'Ben': 11}
countsAda: 14, Ben: 11, Chuck: 1value > 10conditionfilteredAda: 14, Ben: 11later useiterate or modifyinspect each entrycondition trueuse result
How do matching entries flow from the original dictionary into a new dictionary?

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

  • Common mistake

    Comparing the key instead of the value

    What it looks like
    if name > 10:
    Why it fails

    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.

    Do this instead

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

  • Common mistake

    Forgetting the index operator

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

    This compares the key directly with 10. It does not access the value associated with the key.

    Do this instead

    Use the key inside the index operation: if counts[name] == 10:

  • Common mistake

    Using assignment instead of comparison

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

    The filtering condition needs a comparison. Assignment with = is not the comparison operation used to test whether a value equals 10.

    Do this instead
    Use == when testing equality: if counts[name] == 10:
  • Common mistake

    Modifying the dictionary being iterated through

    What it looks like

    Adding or removing entries from counts while the for loop is processing counts.

    Why it fails

    The source material identifies modifying the dictionary during iteration as a common mistake.

    Do this instead

    Collect matching entries in a new dictionary such as filtered, then use that result after the loop.

Practice the Pattern

MEDIUM

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?

  • key >= 80

  • scores[key] >= 80

  • scores[80] >= key

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.

scoresAva: 92, Bo: 76, Cy: 85value >= 80test each entryAva: 92includedCy: 85includedBo: 76left outinspect entriestruetruefalse
Which key-value pairs pass the value condition, and which pairs are left out?

Pattern Summary

  1. 1
    A for loop over a dictionary gives you keys, not values.
  2. 2
    Use the index operator, such as counts[key], to retrieve the value associated with the current key.
  3. 3
    Place the retrieved value in a condition to select entries by their values.
  4. 4
    Filtering selects matching entries; it does not require modifying them.
  5. 5
    Print matching entries immediately or assign them to a new dictionary for later use.

At a glance

  • 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.

Related concepts

More concepts starting with A