Concepts / Iterating Through Dictionaries with For Loops

Iterating Through Dictionaries with For Loops

Composite keys are tuples that combine multiple values into a single dictionary key, created using the syntax dictionary[value1, value2] = result.

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

combined withcombined withmaps toAdafirst value(Lovelace, Ada)one tuple keyAnalystdictionary valueLovelacesecond value
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.

roles = {} roles["Lovelace", "Ada"] = "Analyst" role = roles["Lovelace", "Ada"] print(role)

Output
Analyst
position 1position 2retrievesLovelacevalue 1(Lovelace, Ada)constructed keyAnalystretrieved valueAdavalue 2
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.

containscontainsmaps to(Lovelace, Ada)tuple keyLovelacetuple element 1Adatuple element 2Analystdictionary value
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

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
unpacks position 1unpacks position 2unpacks position 1unpacks position 2(Lovelace, Ada)dictionary keylast = Lovelacefirst loop variablefirst = Adasecond loop variable(Hopper, Grace)next dictionary keylast = Hopperfirst loop variablefirst = Gracesecond loop variable
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.

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

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.

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

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

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

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

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

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

  • Looking up a tuple key in the wrong order.

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

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

  • Treating one tuple element as the entire key.

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

    Fix: Construct the complete tuple key containing both related values.

  • Reversing the loop variables.

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

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