What makes a good dictionary key

Arrays, strings and hash maps Junior Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What happens?

Python 3.13
d: dict[object, str] = {}
d[(1, 2)] = "ok"
d[[1, 2]] = "no"
print(d)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A TypeError: unhashable type: 'list'

Right: lists are mutable, so Python refuses them as keys.

The tuple insert succeeds; the error comes from hashing the list, so the print never runs.

Why not the others?
  • B {(1, 2): 'no'}. A list never compares equal to a tuple key, and it is refused before any comparison.
  • C {(1, 2): 'ok', [1, 2]: 'no'}. That dict cannot exist; the second assignment raises.

30-second answer

A key must be hashable: its hash must never change and equal keys must hash equally. Tuples of immutable values qualify; lists can change after insertion, which would strand the entry in the wrong slot, so Python refuses them. Use tuples, frozensets or frozen dataclasses as composite keys.

Practise saying it · 45 s. No recording, just a timer

Explain what makes a dict key valid.

Say your answer out loud, then check which of these points you covered:

  • Hashable: stable hash
  • Equal keys hash equally
  • Tuples and frozensets as composite keys

Deep dive

The dict stores the key's hash at insertion. If the key could change, its new hash would point to a different slot and lookups would miss.

A tuple that contains a list is not hashable either: hashing a tuple hashes its items.

Custom classes hash by identity by default; define __eq__ and __hash__ together, from the same fields, if equal values should match.

Common mistakes

  • Defining __eq__ without __hash__; Python then sets __hash__ to None and the object is unhashable.
  • Using a float computed by arithmetic as a key and expecting near-equal values to match.

Senior take & follow-ups

The interviewer wants the invariant: hash stable for the key's lifetime and consistent with equality.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you key on a grid cell?

    Show hint

    Use a (row, col) tuple.

  2. How would you key on a set of tags?

    Show hint

    Use a frozenset, which is hashable and ignores order.

What each operation costs: Arrays · Dynamic Arrays · Hash Table · Hash Functions

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.