liveBook · Manning

Unhashable

As explained in Python How-To

An unhashable object is a Python object that cannot serve as a dictionary key or set element because it lacks the required stable hashability.

An unhashable object cannot serve as a dictionary key or set element. Using one in either position raises TypeError because dictionaries and sets rely on stable hash values for retrieval. section 3.5 section 3.5.2

Listing 3.6 Failed creation of dict and set objects
failed_dict = {[0, 2]: "even"}
# ERROR: TypeError: unhashable type: 'list'
 
failed_set = {{"a": 0}}
# ERROR: TypeError: unhashable type: 'dict'

These failed constructions show the restriction directly: lists cannot be dictionary keys, and dictionaries cannot be set elements. section 3.5

Hashability depends on stable hashing. A mutable object could change its contents after insertion, creating a conflict between its old lookup position and its new value. Dictionaries and sets therefore accept common immutable types such as int, float, str, tuple, bool, and None, but reject dict, list, and set. section 3.5.2

Checking hashability

from collections.abc import Hashable items = [{"a": 1}, [1], {1}, 1, "test", (1, 2), None] for item in items: print(type(item).__name__, isinstance(item, Hashable)) # dict False # list False # set False # int True # str True # tuple True # NoneType True Use isinstance(value, Hashable) when code needs to validate a potential dictionary key or set element before insertion. section 3.5.2

When choosing between containers:

  • Use lists and tuples when flexible element storage is the main need. section 3.5
  • Use dictionaries for key-value retrieval and sets for membership-oriented collections, using only hashable keys or elements. section 3.5
  • Remember that immutability commonly accompanies hashability, but the practical test is whether the object is accepted as hashable. section 3.5.2

How Python How-To covers it

How deep it goes
Explains TypeError, stable hash values, mutability conflicts, common types, and runtime checking without descending into hashing algorithms.
Examples
Uses failed dictionary and set constructions, hash calls, a hashability-checking loop, and comparisons of mutable and immutable types.
What it assumes
Assumes familiarity with basic Python containers while defining hashing, hashability, and the relevant exception.
What you can do after
Diagnose TypeError from invalid dictionary keys or set elements and check candidate values with collections.abc.Hashable.
How it connects
Connects unhashable objects with dictionaries, sets, hashing, hashable objects, mutability, and immutability.

Also explained in

Compare how 2 books explain unhashable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.