Pylerno
English

Equality, hashing, and dictionary keys

Two sensors can produce separate Python objects that describe the same reading. To group those readings, decide what makes two keys equal. Start with references and copying and data classes.

On this page

Separate identity from meaning

Imagine labelling a drawer by station and hour. Reprinting the label does not give you a second drawer. Similarly, two objects can occupy different places in memory but identify the same dictionary entry. Use is to ask whether two names refer to one object. Use == to ask whether their values compare equal.

Build a stable key

python
from dataclasses import dataclass

@dataclass(frozen=True)
class Slot:
    station: str
    hour: int

first = Slot("north", 9)
second = Slot("north", 9)
counts = {first: 1}
counts[second] += 1

print(first is second, first == second)
print(len(counts), counts[first])

The first line prints False True. Each constructor call created a new object. The generated equality method compares the two fields. The second line prints 1 2. A dictionary uses a key's hash to locate candidates, then checks equality to identify the entry. Equal keys must have equal hashes. Different keys may still share a hash.

Test a change to the design

Add a third reading for station north at hour 10. Predict the number of entries before running the change. Assigning counts[Slot("north", 10)] = 1 creates a second entry because the hour participates in equality.

A dictionary requires the hash of a stored key to remain stable. Here both fields are immutable and the frozen class prevents ordinary reassignment. Adding a list field can make an instance unhashable even in a frozen class. Keep mutable measurements in the value and immutable identifying fields in the key.

Python data model

Check your understanding

What does this program print?

python
a = [2]
b = [2]
print(a is b)
Choose one answer

Search documentation

Share this page