Sobes.tech
Junior — Middle

How can an object of a class be used as a key in a dictionary in Python?

sobes.tech AI

Answer from AI

To use an object of a class as a key in a Python dictionary, the object must be hashable. This means that the class should implement the __hash__() and __eq__() methods. By default, user-defined class objects are hashable based on their id, but if you override __eq__, you should also define __hash__.

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))

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

my_dict = {p1: "A", p2: "B"}
print(my_dict[p1])  # Outputs "A"

Thus, objects with the same coordinates are considered equal and can be used as keys.