Sobes.tech
Junior — Middle

Can objects of a class be used as keys in a dictionary?

sobes.tech AI

Answer from AI

Objects of a class can be used as keys in a Python dictionary if they are hashable. For this, the class must implement the __hash__() and __eq__() methods. By default, user-defined class objects are hashable if these methods are not overridden, and their hash is based on the object's identifier (memory address).

If you want different objects with the same values to be considered equal keys, you need to implement __hash__ and __eq__() accordingly. For 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))

points_dict = {Point(1, 2): "A point"}
print(points_dict[Point(1, 2)])  # Outputs "A point"

If an object is not hashable (for example, contains mutable fields without implementing __hash__), it cannot be used as a key.