Concepts / Accessing Dictionary Values with the Index Operator

Accessing Dictionary Values with the Index Operator

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

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

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.

counts = { "Ada": 14, "Ben": 11, "Chuck": 1 } for name in counts: if counts[name] > 10: print(name, counts[name])

use keyretrievestest valuetruenameAdacounts[name]index lookup14value14 > 10conditionAdaselected entry
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?

passes conditionchanges valueAda: 14existing entryAda: 14selected unchangedAda: 14existing entryAda: 28modified entry
Does the code select existing entries unchanged, or does it modify the entries before producing the result?

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}
inspect each entrycondition trueuse resultcountsAda: 14, Ben: 11, Chuck: 1value > 10conditionfilteredAda: 14, Ben: 11later useiterate or modify
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

  • Comparing the key instead of the value

    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.

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

  • Forgetting the index operator

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

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

  • Using assignment instead of comparison

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

    Fix: Use == when testing equality: if counts[name] == 10:

  • Modifying the dictionary being iterated through

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

    Fix: 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.

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

Pattern Summary

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

Key Takeaways

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