Python Hashable Dictionary Keys: How to Use Them Correctly
Learn what makes Python objects hashable, how to use custom classes as dictionary keys, and how to avoid mutable-key pitfalls.

To use an object as a Python dictionary key, that object must be hashable. In practical terms, passing it to hash() must return an integer without raising TypeError, and that integer must remain stable while the object is in use. This article explains what makes an object hashable, how to write custom classes that work as dictionary keys, and how to avoid common pitfalls that can silently break lookups.
What Makes an Object Hashable in Python
Hashability depends on two special methods: __hash__ and __eq__. An object is hashable when its __hash__ method returns an integer and its __eq__ method defines equality in a way that is consistent with that hash. The critical invariant is: if two objects compare equal, they must have the same hash. Dictionaries use the hash to locate a bucket and then use equality to confirm a match, so violating that invariant makes dictionary behavior unpredictable.
Most built-in immutable types are hashable: int, float, str, bytes, tuple, and frozenset. Mutable containers such as list, dict, and set are not hashable because their contents can change, which would change their equality. Python sets __hash__ to None for these types, so calling hash([1, 2]) raises TypeError: unhashable type: 'list'.
The Hash Contract: hash and eq
The relationship between __hash__ and __eq__ is a contract. When you define __eq__ in a class without also defining __hash__, Python automatically sets __hash__ to None. This is intentional: two objects that compare equal must share a hash, and without an explicit hash method there is no way to guarantee that. For example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and self.x == other.x and self.y == other.y
p = Point(1, 2)
print(hash(p)) # TypeError: unhashable type: 'Point'To make Point hashable, you must provide __hash__. A straightforward approach is to hash a tuple of the attributes that define equality:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))Now Point(1, 2) can be used as a dictionary key because the hash is derived from the same values used in __eq__, preserving the invariant.
Using Built-in Types as Dictionary Keys
Built-in immutable types are the most common dictionary keys. Strings and integers are used everywhere, but tuples are particularly useful when you need a composite key. For example, a coordinate pair (x, y) can be a tuple key:
d = {}
d[(3, 4)] = 'origin'
print(d[(3, 4)]) # 'origin'A tuple is hashable as long as every element in it is hashable. You can create a tuple with a list inside it, but you cannot hash it or use it as a dictionary key:
key = ([1, 2], 3)
hash(key) # TypeError: unhashable type: 'list'Frozensets are also hashable and can be used when you need an unordered collection of unique values as a key. They are less common than tuples, but useful when order does not matter.
Creating Custom Classes That Work as Keys
When you design a class that should be used as a dictionary key, decide which attributes define equality and make sure those attributes are immutable. If any of those attributes can change after the object is inserted into a dictionary, the hash will change, and the dictionary will no longer find the entry. This is the most frequent bug when using custom objects as keys.
Consider a class representing a user account. If you use the user ID as the equality attribute, that ID should not change. A safe implementation might look like this:
class User:
def __init__(self, user_id, name):
self.user_id = user_id
self.name = name
def __eq__(self, other):
return isinstance(other, User) and self.user_id == other.user_id
def __hash__(self):
return hash(self.user_id)If name changes later, the hash remains stable because it is based only on user_id. If you instead included name in the hash and then changed it, the object would become unfindable in any dictionary where it was already used.
Python's dataclasses provide a convenient way to create immutable, hashable objects. If you set frozen=True, the dataclass generates __hash__ based on the fields, and equality is also field-based:
from dataclasses import dataclass
@dataclass(frozen=True)
class FrozenPoint:
x: int
y: intThis FrozenPoint is automatically hashable and immutable, making it a good choice for dictionary keys without writing boilerplate.
Common Hashability Pitfalls and Errors
The most common error is attempting to use a mutable object as a key. Lists and dictionaries raise TypeError immediately. But subtler errors occur when you define __eq__ without __hash__, or when you mutate an object after using it as a key. The latter does not raise an error at the time of mutation; it silently breaks the dictionary's lookup. For example:
class MutableKey:
def __init__(self, value):
self.value = value
def __hash__(self):
return hash(self.value)
def __eq__(self, other):
return isinstance(other, MutableKey) and self.value == other.value
k = MutableKey(10)
d = {k: 'data'}
k.value = 20
print(d.get(k)) # None, because the hash changedEven if you do not change the object itself, if the hash depends on mutable state, the same problem occurs. The only safe approach is to make the attributes used in __hash__ and __eq__ immutable. This often means using a property without a setter, or making the class frozen.
Another pitfall is overriding __eq__ without also defining __hash__. As mentioned, Python sets __hash__ to None, which makes the class unhashable. This is intentional, but it can surprise developers coming from languages where equality and hashing are independent.
Performance Implications of Custom Hash Functions
Dictionary performance depends on the quality of the hash function. A good hash function distributes keys evenly across the hash table, minimizing collisions. Python's built-in hashing for strings and bytes is highly optimized and randomized by default; integer hashing is deterministic. When you write a custom __hash__, you should aim for a similar distribution. Hashing a tuple of the relevant attributes is usually sufficient because it reuses Python's efficient tuple hashing.
Avoid a hash function that returns a constant, such as return 0. It is legal, but it causes every key to land in the same bucket and makes dictionary lookup effectively O(n). Likewise, a hash based on only a small part of the key can cause clustering. For example, hashing only the first character of a string would be poor.
In practice, you rarely need to micro-optimize hash functions. Python's dictionaries use open addressing to handle collisions, and the built-in tuple and frozenset hashes are well-tested. Focus on correctness first: keep the hash stable and consistent with equality. If profiling later shows slow dictionary lookups, then consider whether the hash distribution is the cause.
Hash Randomization and Security Considerations
Python enables hash randomization by default for strings and bytes, which means values like 'user-1' can have different hashes in different processes. This helps prevent denial-of-service attacks that exploit predictable hash collisions. When a custom object's __hash__ calls hash() on a string attribute, it inherits that randomization. If you write a completely custom integer hash algorithm, you do not automatically get the same protection.
Another subtle issue is that a tuple's hash is not simply the sum of its elements' hashes. Python combines them in a specific, version-dependent way, and string components are randomized by default. For that reason, never persist hash values. Hash values are ephemeral: Python does not guarantee that they remain the same across process runs or Python versions. If you need a stable identifier for an object across runs, use a separate field such as an integer ID or UUID and base equality and hashing on that field. This is common in ORMs and caching systems.
Memory is another practical consideration. Creating many custom key objects adds overhead compared with using tuple keys, especially if every object is small. If you only need a composite value as a key, use a tuple such as (x, y). If you need methods or richer type behavior, a hashable custom class is appropriate.
In summary, using custom objects as dictionary keys is powerful but requires care. Keep the attributes that participate in __hash__ and __eq__ immutable, implement both methods consistently, and do not rely on hash values for persistence. Following these rules lets you use complex key types safely without sacrificing correctness or performance.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.