Concepts / Nested Dictionaries as an Alternative Structure

Nested Dictionaries as an Alternative Structure

Composite keys are tuples used as dictionary keys to organize data by multiple related values simultaneously.

  • Programming

One Entry, Several Identifiers

A dictionary normally uses one key to locate one value. Sometimes, however, a value is identified by several related pieces of information together. A student grade, for example, might be identified by a student ID, a course code, and a year. When the combination is unique, those pieces can be grouped into a tuple and used as one composite key.

A composite key is a tuple used as a dictionary key. The complete tuple is treated as one key, even though it contains multiple components.

containsmaps todictionary(Smith, Alice)complete tuple keygradeone associated value
How do two components in a tuple key map to a single dictionary value?

Building an Exact Lookup

To assign a value with a composite key, place the key components inside the dictionary's square brackets, separated by a comma. The form dictionary[key1, key2] = value is equivalent to dictionary[(key1, key2)] = value. The parentheses are optional in this bracketed syntax because Python recognizes the comma-separated components as a tuple.

Assigning and Retrieving a Grade

Store a grade under the combined key consisting of a last name and a first name, then retrieve it using the same composite key.

Create the entry: The assignment dictionary["Smith", "Alice"] = value creates a tuple key equivalent to ("Smith", "Alice") and associates that complete key with the value.

Match the complete key: To retrieve the value, use dictionary["Smith", "Alice"]. Both components must match the stored tuple key.

Distinguish similar keys: The key ("Smith", "Bob") is different from ("Smith", "Alice"), and ("Johnson", "Alice") is also different from ("Smith", "Alice"). Sharing one component does not make the keys equal.

The value is found only when the lookup uses the same complete tuple key.

combineuse as keyretrievecategory, itemtwo related values(category, item)one composite keydictionary lookupexact tuple matchvalueassociated data
What happens when a tuple such as (category, item) is used to assign or retrieve a dictionary value?

Key Validity and Data Shape

Composite keys must be hashable, which means immutable. Every element inside the tuple must also be hashable. This requirement allows the tuple to be used as a dictionary key.

A composite key is useful when several related pieces of information are needed together to identify one value. The combination may be unique even when no individual component is unique. For example, a student ID may not be unique across schools, and a course code may not be unique across years, while the combined student ID, course code, and year can identify one grade record.

stores bystores withincomposite-keydictionary(student, course)one complete keynested dictionarycoursekey inside student
How is the same multi-part data organized differently with tuple keys versus dictionaries nested inside dictionaries?

Keep the order and meaning of tuple components consistent throughout one dictionary. A lookup using one component order is not the same as a lookup using the reversed order.

Unpacking During Iteration

When a dictionary uses tuple keys, a loop can unpack each key directly into separate variables. The form for var1, var2 in dictionary: receives each tuple key and automatically places its components into var1 and var2. This avoids retrieving a tuple first and then manually extracting its parts.

What do you think happens?

Suppose a dictionary contains the composite keys ("Smith", "Alice") and ("Johnson", "Bob"). During iteration with for last, first in dictionary:, what do last and first receive on each pass?

  • The whole dictionary and its values
  • The two components of the current tuple key
  • Only the first component of each key
  • A newly created nested dictionary
Reveal answer

Answer: The two components of the current tuple key

Each loop variable receives one component of the current tuple key. On one pass, last and first receive Smith and Alice; on another, they receive Johnson and Bob.

unpackcontinueunpack(Smith, Alice)current keylast = Smith, first =Aliceunpacked components(Johnson, Bob)next keylast = Johnson, first= Bobunpacked components
How does a tuple key split into individual variables as the dictionary is traversed?

Reading Components While Traversing

Iterate through a dictionary whose keys contain a last name and a first name, and make each name available as a separate loop variable.

Receive one key: The loop receives a tuple key such as ("Smith", "Alice").

Unpack the tuple: The first loop variable receives Smith and the second receives Alice.

Advance to the next key: The same unpacking happens for the next tuple key, such as ("Johnson", "Bob").

Each tuple key is processed as separate components without manually extracting the elements.

Choosing the Lookup Structure

  • Treating one component as if it were the complete key.

    The dictionary uses the complete tuple for lookup. A single component does not match that composite key.

    Fix: Use the same complete tuple, with every component in the established order.

  • Assuming shared components make two composite keys equal.

    Two composite keys are different when any component differs.

    Fix: Compare the entire tuple, not just one component.

  • Using an unhashable component inside the tuple.

    A composite key must be hashable, and all elements inside the tuple must also be hashable.

    Fix: Use only hashable, immutable key components.

  • Choosing a composite key when lookups usually use one component.

    Composite keys are less clear when values are frequently retrieved for just one component.

    Fix: Consider nested dictionaries or another data structure when one-component lookups dominate.

QuestionComposite-key dictionaryNested dictionary
How is the combined identity represented?As one tuple keyAs keys at multiple dictionary levels
How is a value located?By matching the complete tupleBy moving through nested keys
When is it useful?When several components are needed together for a unique lookupWhen values are frequently retrieved for one component

Practice the Pattern

EASY

A dictionary stores scores using a pair consisting of a category and an item. Describe the composite key used to store the score for category "fruit" and item "apple". Then describe how a loop with two variables could unpack each key while traversing the dictionary.

Hints
  • The two key components form one tuple.
  • The assignment and retrieval forms use the same complete key.
  • Two loop variables receive the two tuple components in order.
MEDIUM

Decide whether a composite-key dictionary or a nested dictionary is clearer for a grade system where lookups are usually made by student ID, with course code as a secondary lookup. Explain your choice.

Hints
  • Focus on which component is most often used first.
  • Consider whether retrieving all values for one student is a common operation.

Key Takeaways

  1. A tuple can act as one dictionary key while representing several related values.
  2. The forms dictionary[key1, key2] = value and dictionary[(key1, key2)] = value work identically.
  3. A lookup must match the complete tuple key, including every component and its order.
  4. Composite keys and all their elements must be hashable.
  5. During iteration, for var1, var2 in dictionary: unpacks each tuple key into separate variables.
  6. Use nested dictionaries instead when lookups frequently focus on one component.

Key Takeaways

  • Composite keys use tuples to combine multiple related values into one dictionary key.
  • Assignment and retrieval must use the same complete tuple structure.
  • Tuple keys can be unpacked directly into separate variables during dictionary iteration.
  • Every tuple component must be hashable.
  • Nested dictionaries may be clearer when lookups commonly begin with one component.