liveBook · Manning

Hashable

As explained in Python How-To

A hashable object is a Python object with a stable hash value and equality behavior that allow it to serve as a dictionary key or set element.

Need a dictionary key or set element? Use a hashable object. Hashable objects provide a consistent hash value and equality behavior, allowing Python to locate them reliably. Dictionaries and sets use hash tables, so lookups and membership checks are efficient. section 3.5 section 3.5.3

Common hashability rules:

  • Use int, float, str, tuple, bool, and NoneType as dictionary keys or set elements. section 3.5.2
  • Do not use dict, list, or set objects directly as keys or set elements; they are unhashable. section 3.5.2
  • Prefer immutable values because changing an object would conflict with the requirement for a consistent hash value. section 3.5.2

Check a value before using it as a key

from collections.abc import Hashable items = [{"a": 1}, [1], {1}, 1, 1.2, "test", (1, 2), True, None] for item in items: print(type(item).__name__, isinstance(item, Hashable)) # dict False # list False # set False # int True # float True # str True # tuple True # bool True # NoneType True hash("Hello World!") # produces an integer hash hash([1, 2, 3]) # TypeError: unhashable type: 'list' 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'

Compare failed dictionary and set construction to see exactly where unhashable list and dictionary objects are rejected. section 3.5

How Python How-To covers it

How deep it goes
Explains hash consistency, collisions, mutability, common types, and runtime checks, but does not detail hash-table implementation protocols.
Examples
Uses failed dictionary and set constructions, hash calls, and a Hashable-based type-checking script.
What it assumes
Assumes familiarity with Python objects, dictionaries, and sets while explaining hash values and mutability from their practical consequences.
What you can do after
Diagnose TypeError failures and select suitable dictionary keys or set elements using Hashable checks.
How it connects
Connects hashability with dictionaries, sets, hashing, hash tables, mutability, and immutability.

Also explained in

Compare how 3 books explain hashable →

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.