Sobes.tech
Junior — Middle

Can an object of a class be used as a key in a dictionary structure?

sobes.tech AI

Answer from AI

In Python, a class object can be used as a dictionary key if it is hashable. To do this, the class must implement the __hash__() and __eq__() methods. By default, user-defined class objects are hashable and compared by identity, 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])  # Will output "A"

If an object is not hashable, it cannot be used as a key.