Sobes.tech
Junior — Middle

What functions must be implemented in a class for its objects to be used as keys in a dictionary?

sobes.tech AI

Answer from AI

For objects of a class to be used as keys in a Python dictionary, the class must implement the __hash__() and __eq__() methods.

  • __hash__() should return a hash value of the object that remains constant during the object's lifetime.
  • __eq__() should define the logic for comparing objects for equality.

It is important that objects considered equal (__eq__ returns True) have the same hash.

Example:

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):
        return hash((self.x, self.y))

p1 = Point(1, 2)
p2 = Point(1, 2)

my_dict = {p1: "A point"}
print(my_dict[p2])  # Will output: A point

Without these methods, objects cannot be used as keys because, by default, objects are not hashable or are compared by id.

What functions must be implemented in a class for its… - sobes.tech