Sobes.tech
Junior — Middle

Explain how hashing is implemented when using a custom class as a key in a dictionary or map.

sobes.tech AI

Answer from AI

In Python, to use a custom class as a key in a dictionary, objects of that class must be hashable. To achieve this, you need to implement the __hash__() and __eq__() methods.

  • __hash__() should return an integer value that will be used as the hash of the key.
  • __eq__() should define when two objects are considered equal, so the dictionary can correctly compare keys.

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

    def __hash__(self):
        return hash((self.x, self.y))

# Usage
points_dict = {}
pt1 = Point(1, 2)
pt2 = Point(1, 2)

points_dict[pt1] = "Point A"
print(points_dict[pt2])  # Will output "Point A" because pt1 == pt2 and hash matches

Thus, the dictionary uses the object's hash for quick access, and the __eq__ method for equality checks.