‹ All Python questions

Python Practice Question 3: Tuple Hashability Dict Keys

Python · Test 1 · question 3 of 10

Data Model & Identityeasy

A caching layer stores responses in a dict whose keys are built from request details. One of the following keys makes the assignment cache[key] = response raise TypeError: unhashable type: 'list'. Which one?

Select one answer
Show answer and explanation

Answer:

  • B. ('GET', ['id', 'name'])

Dict keys must be hashable. Lists are mutable and deliberately unhashable. A tuple is immutable, but that alone does not make it hashable: a tuple is hashable only if every element in it is hashable, because its hash is computed from its elements. The tuple in option B contains a list, so hashing it fails with TypeError: unhashable type: 'list', exactly the error in the stem.

Option A is a tuple of a string, a string and an int, all hashable, so the tuple is hashable.

Option C is a frozenset, the immutable, hashable counterpart of set, and its elements are strings. It is a valid key (and is a common way to key on an unordered group of values).

Option D nests a tuple of strings inside a tuple. Every element is hashable all the way down, so this is the correct way to turn the list in option B into a usable key.

Reference: Glossary: hashable

Practice Test 1 ›