Sub topic 2
What can be a key: hashability
This chapter assumes you can create dictionaries and read values from them. It also assumes you know the difference between mutable and immutable objects, and that you can write a small class with __init__ and __eq__. The goal is to learn exactly which objects Python accepts as dictionary keys, why it rejects the others, and how to design your own key types safely.
The rule: keys must be hashable
A dictionary key must be hashable. An object is hashable if it meets two conditions:
- It has a
__hash__()method that returns an integer, and that integer never changes during the object's lifetime. - It can be compared with
__eq__(), and objects that compare equal always return the same hash.
Python calls hash() on a key when you store it and again when you look it up. The hash value narrows the search to a small part of the dictionary. Equality then confirms the match. The last chapter of this tutorial covers the table behind this. For now, the contract is what matters: equal keys must hash equally, and a key's hash must stay stable.
A tuple works as a key and a list does not:
point = {(1, 2): "A"}
print(point[(1, 2)]) # A
try:
point[[1, 2]] = "B"
except TypeError as exc:
print(exc) # unhashable type: 'list'The TypeError is raised at the moment you try to use the list as a key. A dictionary never holds an unhashable key.
Which built-in types are hashable
Most immutable built-ins are hashable. Mutable containers are not, because their contents can change and so their hash would have to change with them.
| Type | Hashable? | Notes |
|---|---|---|
| `int`, `float`, `complex`, `bool` | Yes | Numbers that compare equal share a hash |
| `str`, `bytes` | Yes | |
| `None` | Yes | |
| `tuple` | Only if every item is hashable | Checked when hashed |
| `frozenset` | Yes, if its elements are hashable | Elements of any set are already hashable |
| `range`, functions, classes, modules | Yes | Hashed by value or by identity |
| `list`, `set`, `dict`, `bytearray` | No | `__hash__` is `None` |
You can test any object by calling hash() on it:
samples = [42, 3.14, "text", None, (1, 2), frozenset({1, 2}),
[1, 2], {1, 2}, {"a": 1}, (1, [2])]
for value in samples:
try:
hash(value)
print(f"{value!r:<16} hashable")
except TypeError as exc:
print(f"{value!r:<16} {exc}")The last sample, (1, [2]), is the surprising one. A tuple is immutable, but it is hashable only if everything inside it is.
Hashable is not the same as immutable
People often say "keys must be immutable". That is a useful shortcut, but it is not exact. Two cases show the gap.
First, an immutable tuple that holds a mutable item is unhashable:
from collections.abc import Hashable
item = (1, [2])
print(isinstance(item, Hashable)) # True (misleading)
def is_hashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
print(is_hashable(item)) # Falseisinstance(x, Hashable) only checks that the type defines __hash__. It does not look inside a tuple. Calling hash() is the reliable test.
Second, a mutable object can be hashable. Instances of an ordinary class are hashable by default, and they hash by identity, so their hash does not depend on their contents:
class Node:
def __init__(self, name):
self.name = name
n = Node("a")
registry = {n: "first"}
n.name = "renamed" # mutation is fine here
print(registry[n]) # firstThis works because the hash comes from the object's identity, not from name. The trade-off is that a different Node("a") is a different key.
Equal numbers are the same key
Dictionary lookup uses equality, and Python considers 1, 1.0 and True equal. They also hash the same, so they collide on purpose:
print(hash(1) == hash(1.0) == hash(True)) # True
d = {1: "int"}
d[1.0] = "float"
d[True] = "bool"
print(d) # {1: 'bool'}The dictionary keeps the first key object (1) and replaces the value each time. This matters when you mix numeric types as keys, for example when one part of a program produces 2 and another produces 2.0.
Floating-point nan is a related edge case. nan != nan, but Python checks identity before equality, so the same nan object can find itself while a fresh one cannot:
nan = float("nan")
d = {nan: 1}
print(d[nan]) # 1
print(d.get(float("nan"))) # NoneAvoid nan as a key.
Hash values are not stable across runs
For strings and bytes, Python randomizes hashes for each process as a defense against collision attacks. Integer hashes are not randomized, but they are an implementation detail too.
print(hash("apple")) # different value on each run of the program
print(hash(7)) # 7Never store hash() results in a file or database, and never use them as identifiers. If you need a stable fingerprint, use hashlib. Also do not rely on the order of a set of strings, which depends on these hashes. A dictionary's iteration order does not depend on them, because it follows insertion order.
Making your own classes hashable
For a user-defined class, Python gives you identity-based equality and hashing. Two rules apply once you customize this behavior.
Rule 1: defining __eq__ without __hash__ makes the class unhashable. Python sets __hash__ to None so that you do not accidentally break the contract that equal objects hash equally.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
try:
{Point(1, 2): "a"}
except TypeError as exc:
print(exc) # unhashable type: 'Point'Rule 2: if you add __hash__, base it on the same fields that __eq__ compares, and make sure those fields never change.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
places = {Point(1, 2): "home"}
print(places[Point(1, 2)]) # homeHashing a tuple of the compared fields is the standard way to combine them.
For simple value types, a frozen dataclass writes both methods for you:
from dataclasses import dataclass
@dataclass(frozen=True)
class Coord:
x: int
y: int
grid = {Coord(0, 0): "origin"}
print(grid[Coord(0, 0)]) # originA plain @dataclass generates __eq__ and sets __hash__ to None, so its instances cannot be keys. frozen=True blocks attribute assignment and makes the class hashable. There is also unsafe_hash=True, which hashes a mutable dataclass. It is "unsafe" for the reason in the next section.
Mutating a key breaks the dictionary
The "stable hash" requirement is not only a rule. If a key's hash changes after insertion, the dictionary can no longer find it. Using the hashable Point above:
p = Point(1, 2)
d = {p: "start"}
p.x = 99
print(d.get(p)) # None: hash now points elsewhere
print(d.get(Point(1, 2))) # None: same hash as before, but p no longer equals it
print(len(d)) # 1: the entry is still storedThe entry still exists. It is just unreachable by lookup, and iterating over the dictionary will still show it. Bugs like this are hard to spot, because nothing raises an error.
Turning unhashable data into a key
Sometimes the natural key is a list, set or dictionary. Convert it to a hashable equivalent first:
cache = {}
tags = ["b", "a"]
cache[tuple(tags)] = 1 # list -> tuple (order matters)
cache[frozenset({"x", "y"})] = 2 # set -> frozenset (order ignored)
config = {"mode": "fast", "level": 3}
cache[frozenset(config.items())] = 3 # dict -> frozenset of pairs
print(cache[("b", "a")]) # 1
print(cache[frozenset({"y", "x"})]) # 2
print(cache[frozenset({"level": 3, "mode": "fast"}.items())]) # 3Choose the conversion that matches the meaning you want:
- A
tuplepreserves order and duplicates, so("a", "b")and("b", "a")are different keys. - A
frozensetignores order and duplicates, so it suits "the same group of things". - The last conversion works only if the dictionary's values are hashable too.
Common errors
TypeError: unhashable type: 'list'(or'dict','set'). You used a mutable container as a key or as a set member. Convert it to a tuple or frozenset, or pick a different key.- The same error for a tuple. Look inside it. One nested list is enough to make the tuple unhashable, and the error message names the inner type.
- Lookups that return
Noneor raiseKeyErrorfor a key you know you stored. Check whether the key object was mutated, or whether__eq__and__hash__disagree. - Two keys collapse into one. Check for
1,1.0andTrue, or for objects whose__eq__is broader than you intended. - A class stops working as a key after you add
__eq__. Add a matching__hash__, or use a frozen dataclass.
Exercise
A teammate writes routes = {("home", ["a", "b"]): 1}. The line fails with a TypeError, even though the key is a tuple. Explain why, and show a change that makes it work while keeping the order of "a" and "b".
Show answer
A tuple is hashable only if all of its items are hashable. The list ["a", "b"] inside the tuple is unhashable, so hashing the whole key raises TypeError: unhashable type: 'list'. Convert the list to a tuple: routes = {("home", ("a", "b")): 1}. A tuple keeps the order, and ("home", ("a", "b")) is fully hashable.
Exercise
What does this code print, and why? class Tag: def _init(self, name): self.name = name def eq_(self, other): return isinstance(other, Tag) and self.name == other.name try: seen = {Tag("py"): 1} print(seen[Tag("py")]) except TypeError as exc: print(exc)
Show answer
It prints unhashable type: 'Tag'. Defining __eq__ without __hash__ makes Python set __hash__ to None, so building the dictionary literal fails before any lookup happens. Adding def __hash__(self): return hash(self.name) would make the lookup print 1, as long as name is never changed while the object is a key.
Exercise
After running the code below, what is d and what is len(d)? Explain.
d = {2: "int"}
d[2.0] = "float"
d[True + 1] = "bool sum"
Show answer
d is {2: 'bool sum'} and len(d) is 1. The values 2, 2.0 and True + 1 (which is 2) are equal and have equal hashes, so each assignment finds the existing key and replaces its value. The dictionary keeps the original key object 2.