Sobes.tech
Junior — Middle

How can you ensure that instances of your class can be used as keys in a dictionary?

sobes.tech AI

Answer from AI

To make instances of your class in Python usable as keys in a dictionary, they must be hashable. To do this:

  1. Implement the __hash__() method, which returns an integer hash value.
  2. Implement the __eq__() method to correctly compare objects for equality.

It is important that objects are immutable with respect to the fields involved in hash calculation, otherwise the dictionary may not work correctly.

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

In this example, two objects with the same coordinates are considered equal and have the same hash, so p2 can be used to access the value in the dictionary where p1 was the key.