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


