Sub topic 2
What can be a key: hashability
This chapter assumes you know basic Python syntax, the core built-in types (str, int, list, tuple), and the difference between mutable and immutable objects. It also assumes you can already build a dictionary with a literal or dict().
The rule
A dictionary key must be hashable. An object is hashable if it has a hash value that never changes during its lifetime, and if it can be compared to other objects with ==. Python gets the hash value by calling the built-in hash() function on the key.
Two objects that compare equal must have the same hash value. This is the rule that makes lookups work. When you ask for d[key], Python hashes key and uses the result to find the right place to look.
print(hash("apple") == hash("apple")) # True
print(hash(42) == hash(42.0)) # True, because 42 == 42.0
print(hash((1, 2)) == hash((1, 2))) # TrueThe last two lines show the equality rule in action. 42 and 42.0 are equal, so they share a hash and count as the same key.
Which built-in types work
Immutable built-in types are hashable. Mutable containers are not, because their contents can change, and a changing content would mean a changing hash.
| Type | Hashable? | Note |
|---|---|---|
| `int`, `float`, `bool` | Yes | `True` equals `1`, so they are the same key |
| `str`, `bytes` | Yes | The most common key types |
| `tuple` | Only if every item is hashable | `(1, [2])` is not hashable |
| `frozenset` | Yes | An immutable version of `set` |
| `list`, `dict`, `set` | No | Raise `TypeError` when hashed |
Tuples as keys
Tuples of immutable items are a good way to use several values as one key, such as grid coordinates. A list is rejected with a TypeError.
point = {(1, 2): "A"}
print(point[(1, 2)]) # A
try:
point[[1, 2]] = "B"
except TypeError as exc:
print(exc) # unhashable type: 'list'A tuple is hashable only when everything inside it is hashable. A tuple that contains a list fails in the same way.
try:
{(1, [2]): "bad"}
except TypeError as exc:
print(exc) # unhashable type: 'list'Notice that the error message names list, the inner object that failed, not tuple.
Why mutable keys are blocked
Suppose Python allowed a list as a key. Python would store the entry using the hash of the list at that moment. If you later changed the list, its hash would change, and Python would look in the wrong place. The entry would be stored but impossible to find. Python avoids this by refusing mutable built-in containers as keys in the first place.
Custom classes
Instances of your own classes are hashable by default. Their hash is based on identity, and two different instances are never equal unless you define __eq__.
class Tag:
def __init__(self, name):
self.name = name
a = Tag("x")
b = Tag("x")
registry = {a: 1}
print(a in registry) # True
print(b in registry) # False, a different objectIf you define __eq__ on a class without defining __hash__, Python sets __hash__ to None and the class becomes unhashable. This is a common surprise.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
try:
{Point(1, 2): "p"}
except TypeError as exc:
print(exc) # unhashable type: 'Point'To fix it, define __hash__ so it agrees with __eq__, and only use fields that do not change. A frozen dataclass or a NamedTuple does this for you.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
grid = {Point(1, 2): "start"}
print(grid[Point(1, 2)]) # startCommon errors
- Using a list as a key. Convert it first with
tuple(my_list). - Using a set as a key. Convert it with
frozenset(my_set). - Mixing
1,1.0andTrueas keys and expecting three entries. They collapse into one. - Defining
__eq__and forgetting__hash__.
Exercise
A learner writes d = {("a", ["b"]): 1} and gets TypeError: unhashable type: 'list'. Why does it fail even though the key is a tuple, and how would you fix it?
Show answer
A tuple is hashable only if all of its items are hashable. The inner list ["b"] is mutable and unhashable, so the whole tuple is unhashable. Replace the list with an immutable value, for example d = {("a", ("b",)): 1}.
Exercise
What does len({1: "a", 1.0: "b", True: "c"}) return, and what is the value stored under the key 1?
Show answer
It returns 1. The keys 1, 1.0 and True are equal and share a hash, so they are one key. The key stays as the first one inserted (1), and the value is replaced each time, so the final value is "c".