Concepts / Writing Conditional Statements

Writing Conditional Statements

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

Selecting Entries by Value

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 important question is not merely how to write an if statement. It is how to connect that condition to the value belonging to the current dictionary key.

When a for loop iterates through a dictionary, Python gives the loop one key at a time. If the condition concerns the corresponding value, retrieve that value with the index operator before testing it. The general pattern is: iterate through a key, look up its value, and let an if statement decide whether the entry should be selected.

loop retrievesindex lookupcomparecountsdictionarynamecurrent keyvalue > 10test the valuecounts[name]corresponding value
How does the loop move from each dictionary key to its corresponding value so it can test the value against a condition?

The Three-Step Filter

  1. The for statement retrieves one dictionary key.
  2. The index operator retrieves the value associated with that key.
  3. The if statement compares the retrieved value with the threshold or other condition.

counts = {'Ana': 14, 'Bo': 7, 'Chuck': 1, 'Dina': 18} for name in counts: if counts[name] > 10: print(name, counts[name])

inspecttruefalsedictionary entrykey and valuevalue > 10conditionfilterednew dictionarynext entrynot selected
How does each dictionary entry that passes the condition move into a new result while rejected entries are left out?

Storing the Filtered Result

Printing a passing entry is useful when inspecting a result immediately. If the selected entries will be used later, place them in a new dictionary instead. The condition remains the same; only the action taken when the condition is true changes.

python
Output (expected)
{'Ana': 14, 'Dina': 18}

This loop does not alter the entries in counts. It selects qualifying key-value pairs and places them in filtered. After the loop, filtered contains only entries whose values exceeded 10. That new dictionary can be passed to other functions, iterated through again, or modified further.

OperationWhat happensTypical result
FilteringSelect entries whose values satisfy a conditionA new dictionary or list containing selected entries
TransformingModify entries that have been selectedEntries with changed contents
keepmodifyFilteringselect qualifying entriesfilteredselected entriesTransformingmodify selected entriesmodified resultchanged entries
What is the difference between selecting only entries that meet a condition and modifying the entries that are selected?

Nested Branches

A nested conditional is a conditional statement placed inside another conditional statement, usually inside one of the outer conditional's branches.

x = 3 y = 5 if x == y: print('x and y are equal') else: if x < y: print('x is less than y') else: print('x is greater than y')

truefalsetruefalsex == youter conditionequal messageouter trueless messageinner truex < yinner conditiongreater messageinner false
What happens next when the outer condition is true or false, and which inner condition branches execute?

Only one complete path executes. Python evaluates the outer condition first. If the selected outer branch contains the inner conditional, Python evaluates the inner condition next. If the other outer branch is selected, the inner conditional is never evaluated.

Indentation and Readability

Indentation shows which statements belong to each conditional block. In a nested structure, the inner if statement is indented farther than the outer if statement, and statements inside the inner branches are indented farther again. Reading the indentation lets you identify which branch controls each action.

  • Comparing the dictionary key instead of its value

    The loop variable is a key. In the described pattern, the condition is supposed to test the value associated with that key.

    Fix: Use the index operator to retrieve the value: if counts[name] > 10:

  • Using assignment where a comparison is required

    The conditional needs to test whether two values are equal.

    Fix: Use the comparison operator: if x == y:

  • Modifying the dictionary being iterated through

    Changing the dictionary during iteration is identified as a common mistake in this filtering pattern.

    Fix: Collect passing entries in a separate dictionary such as filtered.

  • Assuming the nested conditional always runs

    An inner conditional runs only when execution enters the outer branch that contains it.

    Fix: Trace the outer condition first, then decide whether the inner condition is reached.

Trace and Practice

EASY

Create a new dictionary named frequent containing only the entries from counts whose values are greater than 10. Then explain, in order, what happens for each key as the loop runs.

Hints
  • Start with an empty dictionary for the result.
  • Iterate through counts so the loop receives keys.
  • Use the index operator to retrieve the value for the current key.
  • Add the current key and value to the new dictionary only when the condition is true.
MEDIUM

Trace this nested conditional for x = 8 and y = 8. Which message runs? Next, trace it for x = 8 and y = 11. Identify the outer branch and, when reached, the inner branch.

Hints
  • Evaluate x == y before considering x < y.
  • The inner condition is inside the outer else branch.
  • Only one complete path executes for each pair of values.

Key Takeaways

  1. A for loop over a dictionary supplies keys, so filtering by value requires an index lookup such as counts[key].
  2. The if statement decides whether the current entry passes the filter; rejected entries are skipped.
  3. Filtered entries can be printed immediately or collected in a separate dictionary for later use.
  4. Filtering selects entries, while transforming modifies selected entries.
  5. A nested conditional runs only when execution reaches the branch that contains it, and excessive nesting can make code difficult to read.

Key Takeaways

  • Dictionary iteration gives the loop keys, not values.
  • Use the index operator to retrieve the current value before testing it.
  • Store passing entries in a new dictionary when they are needed later.
  • Trace nested conditionals from the outer condition to the reachable inner branch.
  • Avoid unnecessary nesting when clearer logical operators can express the same decision.