Course contentsShow
← Python
Lesson 214 of 1,0604. Data Structures MasteryFree lesson

Ensuring Hashability for Custom Objects

Master the requirements for object hashability by implementing hash and equality methods to allow custom classes as dictionary keys.

In this lesson, you will learn how to make your custom class instances work as keys in dictionaries by defining the __hash__ and __eq__ methods.

Why Custom Objects Need Special Care

By default, all custom objects are "hashable," but they rely on their unique memory address (their identity) to determine equality. This means two different objects with identical data are treated as distinct keys by a dictionary. If you want two instances with the same values to be treated as the same key, you must manually define how Python should "hash" them and compare them.

Implementing the Requirements

To make a class hashable, you must satisfy two rules:

  1. Consistency: You must implement __eq__ to define when two objects are equal.
  2. Hashing: You must implement __hash__ to return an integer that represents the object’s data. Crucially, if two objects are equal according to __eq__, they must return the same hash value.

Consider a Point class representing coordinates:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if not isinstance(other, Point):
            return False
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        # We return a hash of a tuple of the data used in equality
        return hash((self.x, self.y))

# Usage
data = {Point(1, 2): "Origin-ish"}
print(data[Point(1, 2)])  # Successfully retrieves "Origin-ish"

The Immutable Rule

For your object to remain a stable dictionary key, it should ideally be immutable. If you change the attributes used in __hash__ after the object is inserted into a dictionary, the object's hash will change, effectively "losing" it inside the dictionary. This is why we often use tuples inside __hash__, as tuples are immutable and their contents are easy to hash.

By defining these two methods, you transform your custom objects from mere containers into robust data structures that behave predictably within Python's high-performance lookup systems.

Key Takeaway: To use custom objects as dictionary keys, implement __eq__ for value comparison and __hash__ to generate a consistent integer ID based on that same data.