Hashable Values and Collection Keys
Hash tables use a hash to locate candidate keys and equality to decide which key is present.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Preserve the key rule
An object suitable as a Python hash key must keep its hash stable over its lifetime. Equal objects must have equal hashes. A coordinate tuple of integers usually meets both rules. A list can change its content and is unhashable. Review mutability before choosing a key representation.
Test a composite key
A dictionary lookup by (2, 5) finds an entry stored under an equal tuple, even if the tuple was constructed later. A tuple containing a list remains unhashable because the tuple's hash depends on its elements. The distinction between identity and equality determines why equal tuples can retrieve the same entry.[1][2]
Keep a lookup key stable for the life of its entry
A map from a coordinate to a stored color might use a pair of integers as its key. Two pairs containing the same coordinates compare equal and must have equal hashes under the usual key contract. A collision between different coordinates is possible. The table uses an equality check to distinguish keys with identical hash values. Those values alone do not establish equality. See hash bucket collisions for a trace of that distinction.
Choose an immutable observation when values can change
A list of open work areas can grow and shrink as the caller edits. A tuple of the current area identifiers can record a snapshot to use as a key if each identifier is hashable. If a nested element still changes, copying only the outer shape might not preserve the key's full semantics.
Decide whether reordering the chosen areas matters. A tuple preserves order, while an immutable set representation can ignore order and duplicates under a membership contract. Test an equal key rebuilt from the source and a changed key that should miss. Set and sequence models explain the representations used by those tests.