Concepts / Iterating Through Dictionaries with For Loops

Iterating Through Dictionaries with For Loops

A for loop can traverse a dictionary whose keys are tuples.

  • Programming

One Key, Two Values

A dictionary key does not have to contain only one value. A tuple can combine two related values into one composite key. The dictionary then connects that complete tuple key to one result. This is useful when the pair of values identifies the entry more precisely than either value by itself.

Adafirst value(Lovelace, Ada)one tuple keyAnalystdictionary valueLovelacesecond valuecombined withcombined withmaps to
How do two values combine into one tuple key, and how does that key connect to its dictionary value?

Retrieving the Matching Value

To retrieve a value, construct the same tuple key in the same order. The expression dictionary[value1, value2] retrieves the value associated with that specific tuple key. The key must represent the particular pair you want to find.

Code walkthrough
roles = {}
roles["Lovelace", "Ada"] = "Analyst"

role = roles["Lovelace", "Ada"]
print(role)
  1. 1
    The assignment creates the tuple key (Lovelace, Ada).
  2. 2
    The lookup constructs that same tuple key and uses it to access the dictionary value.
  3. 3
    The result of the lookup is Analyst.
  • The empty dictionary is prepared for entries.
  • A tuple key containing two related values is assigned the value Analyst.
  • The same tuple format retrieves the associated value.
  • The retrieved value is displayed.
Output
Analyst
Lovelacevalue 1(Lovelace, Ada)constructed keyAnalystretrieved valueAdavalue 2position 1position 2retrieves
What exact key must be constructed to retrieve the value associated with a particular pair of related values?

Order Matters in Tuple Keys

Tuple keys are immutable and order-sensitive. That means (last, first) and (first, last) are different keys because their elements occur in different positions. Both can exist as separate keys in the same dictionary. A lookup must use the tuple arrangement that identifies the intended entry.

(Lovelace, Ada)tuple keyLovelacetuple element 1Adatuple element 2Analystdictionary valuecontainscontainsmaps to
What does the dictionary contain when a tuple is used as a key, and how are the tuple elements related to the stored result?
Tuple keyMeaning for lookup
("Lovelace", "Ada")One specific key arrangement
("Ada", "Lovelace")A different key arrangement

Changing the order changes the tuple key.

Unpacking Keys During Iteration

A for loop can traverse a dictionary whose keys are tuples. With tuple assignment in the loop, the two elements of each tuple key are unpacked automatically into separate variables. This lets the loop work with each related value independently while still traversing the dictionary by its complete composite key.

python
Output
Lovelace Ada
Hopper Grace
(Lovelace, Ada)dictionary keylast = Lovelacefirst loop variablefirst = Adasecond loop variable(Hopper, Grace)next dictionary keylast = Hopperfirst loop variablefirst = Gracesecond loop variableunpacks position 1unpacks position 2unpacks position 1unpacks position 2
How do the two values in each tuple key become separate variables as the loop processes each dictionary entry?

Choosing the Key Shape

Use a composite key when multiple values belong together and the pair is needed to distinguish one dictionary entry from another. A single-value key represents only one identifying value. A tuple key preserves both related values as one key, so the dictionary can distinguish entries using the complete pair.

Adaone identifying valueone resultdictionary value(Lovelace, Ada)two related valuesone resultdictionary valuemaps tomaps to
What information is lost or made ambiguous with a single-value key, and how does a composite key distinguish related records?
Worked example

Representing a Related Pair

Create a dictionary entry for the pair Lovelace and Ada, retrieve its value, and then unpack the pair while traversing the dictionary.

  1. 1
    Create the dictionary

    Start with an empty dictionary so that a tuple key can be added.

  2. 2
    Create the composite key

    Use roles["Lovelace", "Ada"] to create a tuple key containing both related values.

  3. 3
    Store the result

    Assign Analyst to the tuple key so the complete pair maps to that result.

  4. 4
    Retrieve the result

    Use roles["Lovelace", "Ada"] again. The same tuple format retrieves Analyst.

  5. 5
    Traverse the key

    Use for last, first in roles so the tuple elements become the separate variables last and first.

Result

The pair is preserved as one composite key, its value can be retrieved with the same ordered pair, and tuple assignment separates the pair during iteration.

Practice the Traversal

EASY

Suppose a dictionary uses the tuple key ("Hopper", "Grace"). Write the for-loop header that unpacks the first tuple element into last and the second tuple element into first.

Hints
  • The loop needs two variables because each key contains two tuple elements.
  • Place last first and first second so the variable positions match the tuple positions.
  • The loop traverses the dictionary itself.

What do you think happens?

What values will the loop variables receive when the current dictionary key is ("Hopper", "Grace") and the loop header is for last, first in roles?

  • last receives Hopper and first receives Grace

  • last receives Grace and first receives Hopper

  • Both variables receive the complete tuple

Reveal answer
Answer:

last receives Hopper and first receives Grace

Tuple assignment unpacks the first tuple element into the first loop variable and the second tuple element into the second loop variable.

Mistakes with Composite Keys

  • Common mistake

    Looking up a tuple key in the wrong order.

    What it looks like

    An entry was created with ("Lovelace", "Ada"), but the lookup uses ("Ada", "Lovelace").

    Why it fails

    Tuple keys are order-sensitive, so the two arrangements are different keys.

    Do this instead

    Use the same values in the same order when retrieving the value.

  • Common mistake

    Treating one tuple element as the entire key.

    What it looks like

    Trying to retrieve the entry with only "Ada".

    Why it fails

    The dictionary entry is associated with the complete tuple key, not with one element by itself.

    Do this instead

    Construct the complete tuple key containing both related values.

  • Common mistake

    Reversing the loop variables.

    What it looks like

    Using for first, last in roles when the tuple is arranged as (last, first).

    Why it fails

    Tuple assignment follows position, so the first variable receives the first tuple element.

    Do this instead

    Arrange the loop variables in the same positional order as the tuple elements.

Key Takeaways

  • A tuple can combine multiple related values into one composite dictionary key.
  • Create and retrieve a tuple-key entry with the same ordered tuple format.
  • Tuple keys are immutable and order-sensitive, so reversing their elements produces a different key.
  • A for loop can use tuple assignment to unpack each tuple key into separate variables.
  • Composite keys preserve multiple related values when a single-value key would not distinguish the complete pair.

Related concepts

More concepts starting with I