Using Composite Keys in a Dictionary

A composite key joins several fields into one lookup identity. Every field participating in that identity needs a stable representation.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Avoid ambiguous concatenation
  2. Choose the field order
  3. Test values that cross component boundaries
  4. Check validity beyond immutability of the outer key

Avoid ambiguous concatenation

Combining text fields "ab" and "c" without a boundary yields the same string as combining "a" and "bc". A tuple preserves both positions and avoids this artificial collision. See hashable values for when such tuples can be keys.

Choose the field order

A measurement keyed by station and day should place the same field first at write and read time. Test two days for one station and one day across two stations. Named units and meanings help document what those fields represent.[1]

Test values that cross component boundaries

A site code and a local account number can form a key such as ("ab", "12"). Joining the parts without a delimiter would collide with ("a", "b12"). A tuple preserves both positions and their equality. If key components need normalization, apply it separately to each before storage and lookup. Keeping display labels outside the key lets them change without breaking references. See stable collection identifiers.

Check validity beyond immutability of the outer key

A Python tuple containing a list still cannot act as a dictionary key because the list itself is unhashable. Freeze the list only when its order and duplicates truly define identity. If identity does not care about order, choose a representation that expresses that relation explicitly. Test two equal composite keys built independently and two differing in just one field. See hashable values.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩