Sub topic 4
Why some objects can be keys and others cannot
This chapter assumes you know Python's basic types (int, str, list, tuple, dict, set) and the difference between mutable and immutable objects from the earlier chapters. It explains the rule behind the error TypeError: unhashable type: 'list', so you can predict which objects work as dict keys or set elements and which do not.
The rule in one sentence
A dict key or set element must be hashable. That means it has a hash value that never changes during its lifetime, and it can be compared with == to other objects. Equal objects must have equal hash values.
Python checks this when you insert or look up an item. You can run the same check yourself with the built-in hash() function:
for value in [42, 3.5, "text", (1, 2), frozenset({1}), None, True]:
print(type(value).__name__, hash(value) == hash(value))Every line prints True, because hashing the same object twice gives the same number. Now try the types that fail:
for value in [[1, 2], {"a": 1}, {1, 2}, bytearray(b"x")]:
try:
hash(value)
except TypeError as e:
print(e)The output is:
unhashable type: 'list'
unhashable type: 'dict'
unhashable type: 'set'
unhashable type: 'bytearray'All four are mutable containers. That is not a coincidence, and the next section explains why.
What a hash is for
A hash is an integer computed from an object's value. Dicts and sets use it to avoid scanning every item. Instead of comparing your key to each stored key, Python converts the key to a hash, uses the hash to jump to a position in an internal table, and compares only against the few entries stored there.
This is why lookup in a dict or set takes roughly constant time on average, a point the performance chapter returns to. It also explains the two requirements that define hashability:
- The hash must stay the same while the object is in the table. If it changed, Python would look in the wrong slot and fail to find an item that is still there.
- Equal objects must have equal hashes. If
a == bbuthash(a) != hash(b), the two could land in different slots, and the dict or set would treat them as different keys.
The reverse is not required. Two different objects can share a hash, which is called a collision. Python handles collisions by probing and comparing with ==, which costs a little time but does not break correctness.
A list is unhashable because its value can change. If [1, 2] were a key and you then appended 3, its hash would have to change, and the dict would lose track of it. Python avoids this by refusing to hash lists at all.
Which built-in types are hashable
| Type | Hashable? | Reason |
|---|---|---|
| `int`, `float`, `bool`, `complex` | Yes | Immutable numbers |
| `str`, `bytes` | Yes | Immutable sequences |
| `None` | Yes | Single constant object |
| `tuple` | Only if all items are hashable | Hash is built from the items' hashes |
| `frozenset` | Only if all items are hashable | Items of a set must already be hashable |
| `range` | Yes | Immutable |
| `list`, `dict`, `set`, `bytearray` | No | Mutable, so `__hash__` is `None` |
| Instances of your own classes | Yes by default | Hash is based on object identity |
Note that "immutable" is not the same as "hashable". Immutability is the usual reason an object can be hashed, but the actual test is whether the object defines a hash. The tuple row shows the difference.
Tuples are hashable only if their contents are
A tuple computes its hash by combining the hashes of its items. If any item is unhashable, the tuple is too:
good = (1, "a", (2, 3))
print(hash(good) == hash((1, "a", (2, 3)))) # True
bad = (1, [2, 3])
try:
hash(bad)
except TypeError as e:
print(e) # unhashable type: 'list'This matters when you build composite keys. A tuple of numbers and strings works as a key. A tuple that contains a list does not, even though the tuple itself cannot be changed. The frozenset and composite-key chapter covers converting such data into a hashable form.
Equality and hashing are linked
Dicts decide whether two keys are "the same" using ==, not type. Numbers that compare equal also hash equally, so they collide on purpose:
print(1 == 1.0 == True) # True
print(hash(1), hash(1.0), hash(True)) # 1 1 1
d = {1: "int"}
d[1.0] = "float"
d[True] = "bool"
print(d) # {1: 'bool'}The dict ends up with one key. The first key object (1) stays, and each later assignment replaces its value. This is correct behavior, but it surprises people who mix numeric types or use booleans as keys alongside integers.
Strings and bytes are different. "a" == b"a" is False, so they are separate keys.
Hash values are not stable across runs
For strings and bytes, Python adds a random seed at startup (hash randomization), so hash("abc") differs from one run of the interpreter to the next. This defends against attacks that craft many colliding keys. Two practical consequences follow:
- Never store
hash()results in files or databases as identifiers. - Never rely on the iteration order of a set of strings. It can change between runs. Use
sorted()when you need predictable output, as the earlier set examples did.
Dicts are different. They preserve insertion order, and that order does not depend on hash values.
For integers, hashes are predictable, but you should still not depend on specific values. A small curiosity: in CPython hash(-1) is -2, because -1 is reserved internally as an error signal.
Hashing your own classes
By default, instances of a class hash by identity. Two separately created objects are never equal, even if their attributes match:
class Token:
pass
a = Token()
b = Token()
print(a == b) # False
registry = {a: "first"}
print(a in registry) # True
print(b in registry) # FalseThat is often what you want for objects that represent a unique thing, such as a connection or a user session.
Defining `__eq__` removes the default hash
When you want value-based equality, you define __eq__. Python then sets __hash__ to None for that class. It does this to keep the rule that equal objects have equal hashes, since the old identity-based hash would no longer match your new equality.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
p = Point(1, 2)
try:
{p: "start"}
except TypeError as e:
print(e) # unhashable type: 'Point'The easy fix: a frozen dataclass
A frozen dataclass generates __eq__ and a matching __hash__ from its fields, and it blocks attribute assignment after creation:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
seen = {Point(1, 2): "start"}
print(seen[Point(1, 2)]) # start
print(hash(Point(1, 2)) == hash(Point(1, 2))) # True
try:
Point(1, 2).x = 5
except AttributeError as e:
print(type(e).__name__) # FrozenInstanceErrorFrozenInstanceError is a subclass of AttributeError, so the except clause catches it. Note that a plain @dataclass with the default eq=True and frozen=False sets __hash__ to None, and it is unhashable for the same reason as Point above.
Writing `__hash__` by hand
If you do write both methods yourself, base the hash on exactly the fields that __eq__ compares, and combine them with a tuple:
class Version:
def __init__(self, major, minor):
self._major = major
self._minor = minor
@property
def major(self):
return self._major
@property
def minor(self):
return self._minor
def __eq__(self, other):
return isinstance(other, Version) and (self._major, self._minor) == (other._major, other._minor)
def __hash__(self):
return hash((self._major, self._minor))
print({Version(3, 12): "current"}[Version(3, 12)]) # currentThe read-only properties signal to callers that the fields should not be changed. Python cannot enforce this, so it remains a convention.
What goes wrong when a key's hash changes
Python trusts you to follow the contract. If you define a hash from mutable fields and then change those fields, the object is still in the table, but in a slot that no longer matches its hash:
class Box:
def __init__(self, v):
self.v = v
def __eq__(self, other):
return isinstance(other, Box) and self.v == other.v
def __hash__(self):
return hash(self.v)
b = Box(1)
d = {b: "found"}
b.v = 2
print(b in d) # False
print(Box(1) in d) # False
print(len(d)) # 1The first lookup hashes the new value 2 and checks the wrong slot. The second lookup finds the right slot, but the stored key now compares unequal to Box(1). The entry is still counted by len(d) but cannot be reached by lookup. Nothing raises an error. This is why the rule is "hash only immutable state," and why built-in mutable types refuse to be hashed.
A special case: NaN
float("nan") is hashable, but it is not equal to itself:
nan = float("nan")
print(nan == nan) # False
d = {nan: "x"}
print(d[nan]) # x
print(d.get(float("nan"))) # NonePython's lookup first checks whether the stored key is the very same object (identity) before calling ==. That is why d[nan] succeeds with the same object, and a different NaN object fails. Avoid NaN as a key. If you must clean data containing NaN before counting or grouping, remove or replace it first.
Practical checklist
- Want to use a value as a key and it is a list? Convert it to a tuple:
tuple(items). - Want to use a set as a key or inside another set? Convert it to a
frozenset. - Have a tuple with a list inside? Convert the inner list to a tuple too, or choose a different key design.
- Want value-based identity for your own class? Use
@dataclass(frozen=True), or define__eq__and__hash__together on immutable fields. - Seeing
unhashable type? Read the type named in the message. It tells you which object, possibly nested inside a tuple, is the problem.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `unhashable type: 'list'` when building a dict | List used as a key | Use a tuple |
| `unhashable type: 'list'` for a tuple key | Tuple contains a list | Convert the inner list to a tuple |
| `unhashable type: 'set'` in a set of sets | Sets cannot contain sets | Use `frozenset` for inner sets |
| Custom class suddenly unhashable | `__eq__` defined without `__hash__` | Add `__hash__`, or use a frozen dataclass |
| Key exists but lookup fails | Hash depended on a field that was changed | Make key fields immutable |
| `1` and `True` overwrite each other | They are equal and hash equally | Keep numeric and boolean keys in separate dicts |
Exercise
Which of these raise a TypeError when used as a dict key, and why? (a) (1, 2, 3) (b) (1, [2, 3]) (c) frozenset({1, 2}) (d) {1, 2}
Show answer
(b) and (d) raise TypeError. (b) is a tuple that contains a list, and a tuple's hash needs all of its items to be hashable. (d) is a plain set, which is mutable and has no hash. (a) and (c) work, because a tuple of ints and a frozenset of ints are both hashable.
Exercise
What does this code print, and why? d = {}; d[2] = "a"; d[2.0] = "b"; d[True + 1] = "c"; print(d, len(d))
Show answer
It prints {2: 'c'} 1. The values 2, 2.0, and True + 1 (which is the int 2) are equal and have equal hashes, so they are the same key. The first inserted key object, 2, is kept, and the value is replaced each time, ending with "c".
Exercise
A class defines __eq__ comparing self.name but does not define __hash__. A colleague adds def __hash__(self): return hash(self.name), and name can be reassigned later. What can go wrong, and what is a safer design?
Show answer
If an instance is already stored in a dict or set and its name changes, its hash changes while it stays in the old slot. Lookups then fail even though the object is still counted in len(). A safer design makes name read-only (for example a frozen dataclass), or avoids using such objects as keys and keys on an immutable identifier such as an ID instead.