Ch. 9 · Python

Python Hashability and Dictionary Keys

Python Hashability and Dictionary Keys. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Hashable keys must maintain compatible equality and stable hash behavior while used in collections. Mutable containers typically cannot be keys.

Before you start

You should know Python functions, collections and exceptions. Use a small isolated script or interactive session to trace the example. Pay attention to when objects are created and when work executes; iteration, binding and mutation can happen at different points in a program.

The practical goal is to reason through this situation: A tuple of immutable IDs can be a composite dictionary key. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Define stable key meaning

Equality and hashing must agree for the duration of collection membership.

Step 2: Inspect every component

An outer tuple is unhashable if it contains an unhashable list.

Step 3: Use immutable representations

A tuple of numeric coordinates is a suitable ordinary composite key.

Worked scenario

A tuple of immutable IDs can be a composite dictionary key.

locations = {(3, 4): 'checkpoint'}
print(locations[(3, 4)])  # checkpoint
# locations[([3], 4)] = 'invalid'  # TypeError
python

For custom classes, mutable equality fields can undermine lookup even when hash exists. Stable representation matters more than merely implementing a method.

Common mistake

A tuple containing a list is not hashable merely because the outer container is a tuple.

Verify the behavior

Test equal separate tuple keys and an unhashable nested member; review custom key mutation.

Interview exercise

Choose a key for coordinates.

Answer and reasoning

Use a tuple of numeric values and avoid changing equality-relevant state in custom key objects.

Continue learning

Compare the scenario with the Python interview questions and test your understanding with the Python MCQs. For terminology and implementation details, consult the reference material.

More in Python

read ✓Python · hard

Python asyncio.gather and Timeouts

Run coroutines concurrently with asyncio.gather, enforce timeouts, and handle partial failures and cancellation correctly.

~2 min readread →
read ✓Python · mid

Python Bounded Async Worker Queues

Use asyncio.Queue and a fixed worker pool to bound pending work. Trace backpressure, shutdown and failure ownership.

~3 min readread →
read ✓Python · mid

Python Asyncio and Blocking Functions

Python Asyncio and Blocking Functions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc