Python Hashing and Dictionary Keys
What you will learn
- How a dictionary uses a hash to find values fast
- What hashable means, and which types are and are not
- Why keys must not change
- The rule that equal values have equal hashes
- That string hashes change between runs
- How to make your own classes usable as keys
- The oddities of
nan
1. The idea: find a value without searching
To find a key in a list, Python has to look at the items one by one. A dictionary does not search. It turns the key into a number, called its hash, and uses that number to jump straight to the right place. Such a structure is called a hash table.
print(hash(42), hash("a") == hash("a"), hash("a") == hash("b"))
42 True False
The steps for d[key] are, in simple terms:
- Work out
hash(key): a whole number. - Use that number to pick a slot in a table.
- Check that the key stored there equals your key. If yes, return its value.
If two different keys land in the same slot (a collision), Python checks the next slot, and so on. Because collisions are rare, a lookup takes about the same time whether the dictionary has ten keys or ten million. In a test on one computer, searching for the last of 100,000 numbers took more than 100 times longer in a list than in a set, while a dictionary and a set took about the same time as each other (lessons 7.7 and 10.3).
Quick check: why is `key in a_dict` fast even for a huge dictionary?
Python uses the key's hash to go straight to a slot, instead of looking through all the keys.
2. What "hashable" means
An object is hashable when it has a hash value that never changes during its life, and when objects that are equal have the same hash. Only hashable objects can be dictionary keys or set members.
| Hashable | Not hashable |
|---|---|
int, float, bool, complex |
list |
str, bytes |
dict |
tuple (if all its items are hashable) |
set |
frozenset |
bytearray |
None, range |
a tuple that contains a list |
for v in ["(1, 2)", "[1]", "{1}", "{'a': 1}", "(1, [2])", "(1, (2, [3]))"]:
try:
hash(eval(v))
print(v, "is hashable")
except TypeError as e:
print(v, "->", e)
(1, 2) is hashable
[1] -> unhashable type: 'list'
{1} -> unhashable type: 'set'
{'a': 1} -> unhashable type: 'dict'
(1, [2]) -> unhashable type: 'list'
(1, (2, [3])) -> unhashable type: 'list'
The pattern: the immutable types are hashable, and the mutable ones are not. A tuple is hashable only if everything inside it is, even deep inside, as the last line shows.
3. Why keys must not change
Imagine a list could be a key. You store {[1, 2]: "x"}: Python hashes the list, and puts the pair in the slot that number picks. Then you change the list to [1, 2, 3]. Its hash changes, so the key now points to the wrong slot: lookups would fail, and the pair would be lost in the table. To prevent this, Python allows only keys that cannot change:
m = [1, 2]
{m: 1}
TypeError: unhashable type: 'list'
This is why you use a tuple for a coordinate key, and a frozenset for a key that is a set of things:
d = {(1, 2): "pair"}
print(d[1, 2], (1, 2) in d, ((1, 2),) in d)
fs = {frozenset([1, 2]): "set key"}
print(fs[frozenset([2, 1])])
pair True False
set key
A frozenset is an immutable set (chapter 10), and frozenset([1, 2]) equals frozenset([2, 1]) whatever the order.
4. Equal values, equal hashes
Python requires a == b to imply hash(a) == hash(b). That is why 1, 1.0 and True act as one key (lesson 9.1):
print(hash(1) == hash(1.0) == hash(True))
print({1: "a"}.get(1.0), {1.0: "a"}.get(True), {0: "z"}.get(False), {"1": "s"}.get(1))
True
a a z None
The reverse is not required: different values may share a hash (a collision). That is allowed; the table then compares the keys to tell them apart. And "1" (text) is a different key from 1 (number).
Some oddities
In CPython, the hash of an integer is usually the integer itself, with a few special cases, so you should never rely on exact hash numbers:
print(hash(42), hash(-1), hash(-2))
print(hash(2 ** 61 - 1), hash(2 ** 61))
42 -2 -2
0 1
hash(-1) is -2 because the value -1 is reserved inside CPython to signal an error. Treat hash numbers as internal details: the only promises are the two rules above.
5. String hashes change between runs
For text and bytes, Python adds a random value to the hash every time the program starts. It does this to protect programs from attackers who could feed them many keys that all collide and make them slow. The effect is easy to see by running the same line twice:
print(hash("python"))
Two runs gave two different numbers on the test computer (and the hash of the number 1234 was the same in both runs). The consequences:
- Never save hash values to a file, or send them to another program, expecting them to stay the same.
- Never depend on the order of a
setof strings. It can change between runs. A dictionary is safe, because it keeps insertion order (lesson 9.5). - Setting the environment variable
PYTHONHASHSEEDto a fixed number makes the hashes repeatable, which is useful for tests. In the test, withPYTHONHASHSEED=0, two runs gave the same hash.
6. Your own classes as keys
A class you write (classes are chapter 13) is hashable by default, and two objects are equal only if they are the same object:
class P:
def __init__(self, x):
self.x = x
a = P(1)
b = P(1)
print(a == b, len({a, b}))
False 2
Two separate P(1) objects count as different keys. To make equal-looking objects count as one key, define __eq__ (when are two objects equal?) and __hash__ (a hash built from the same data). They must agree:
class R:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return isinstance(other, R) and self.x == other.x
def __hash__(self):
return hash(self.x)
print(R(1) == R(1))
print(len({R(1), R(1), R(2)}))
print({R(5): "five"}[R(5)])
True
2
five
If you define __eq__ but forget __hash__, Python removes the hash, to keep the rules safe. The class becomes unhashable:
class Q:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return isinstance(other, Q) and self.x == other.x
hash(Q(1))
TypeError: unhashable type: 'Q'
The data in a hashable object should not change while it is in a dictionary or set. The easiest safe route is a frozen dataclass (lesson 13.11), which provides __eq__ and __hash__ for you:
from dataclasses import dataclass
@dataclass(frozen=True)
class F:
x: int
y: int
print({F(0, 0): "origin"}[F(0, 0)])
origin
A plain @dataclass (not frozen) is not hashable, because its fields can change. A named tuple is hashable (lesson 8.4).
7. The strange case of nan
nan is not equal to itself (lesson 3.1), and that breaks the "equal means same hash" idea. It is also not even equal to another nan:
n1 = float("nan")
n2 = float("nan")
d = {n1: "a"}
print(n1 in d, n2 in d)
print(len({n1, n2}))
True False
2
The lookup with n1 works, because Python first checks whether it is the very same object, and only then compares values. A different nan fails. So nan makes a poor key: avoid it.
Worked example: a cache keyed by a record
A function is slow, so we remember its results in a dictionary. The key is the pair of inputs, so it must be a tuple (hashable).
cache = {}
calls = []
def slow_area(width, height):
calls.append((width, height))
return width * height
def area(width, height):
key = (width, height)
if key not in cache:
cache[key] = slow_area(width, height)
return cache[key]
print(area(3, 4), area(3, 4), area(5, 2), area(3, 4))
print(len(calls), len(cache))
print(sorted(cache))
12 12 10 12
2 2
[(3, 4), (5, 2)]
| Call | Key | Computed? |
|---|---|---|
area(3, 4) |
(3, 4) |
yes (first time) |
area(3, 4) |
(3, 4) |
no, found in the cache |
area(5, 2) |
(5, 2) |
yes |
area(3, 4) |
(3, 4) |
no |
Only two real calculations were needed for four calls. If the inputs were lists, they could not be keys, and you would turn them into tuples first. (Python also has a ready-made cache, functools.lru_cache, lesson 17.5.)
Common mistakes
- Using a list or a set as a key. Use a tuple or a
frozenset. - Using a tuple that contains a list as a key.
- Depending on exact
hash()values or on set ordering of strings. They change between runs. - Defining
__eq__without__hash__and being surprised that the class is unhashable. - Changing an object's data while it is a key or in a set.
- Using
nanas a key.
Key takeaways
- A dictionary uses
hash(key)to jump to a slot, so lookups take about the same time however big it is. - Keys must be hashable: immutable and with equal objects giving equal hashes; lists, dictionaries and sets are not.
- A tuple is hashable only when all its items are; use
frozensetfor set-like keys. 1,1.0andTrueare one key; string hashes change between runs, so never store them.- A class with
__eq__needs a matching__hash__to be a key; a frozen dataclass does it for you.
Practice
1. Which can be a dictionary key: "a", [1], (1, 2), {1}, 3.5?
Show answer
"a", (1, 2) and 3.5. A list and a set are mutable, so they are not hashable.
2. Why is {(1, [2]): "x"} an error?
Show answer
The tuple contains a list, which is unhashable, so the whole tuple is unhashable.
3. How many keys does {1: "a", 1.0: "b", True: "c"} have?
Show answer
One. 1, 1.0 and True are equal and have the same hash, so they are the same key.
4. Why must you never save hash("hello") to a file for later use?
Show answer
String hashes are randomised for each run of Python, so the number will be different next time.
5. A class defines __eq__ only. What happens to hash(obj)?
Show answer
It raises TypeError: unhashable type. Defining __eq__ without __hash__ removes the hash. Define both, so that equal objects have equal hashes.
6. Which structure is the best way to use two numbers (row, column) as one dictionary key?
Show answer
A tuple, (row, column), which is immutable and hashable.