Sobes.tech
Junior — Middle

How can a custom object be used as a key in a data structure, such as a dictionary or hash table?

sobes.tech AI

Answer from AI

In Python, to use a custom object as a dictionary key, it must be hashable. This means that the class should implement the __hash__() and __eq__() methods so that objects with the same values have the same hash and are considered equal.

Example:

class MyKey:
    def __init__(self, id):
        self.id = id

    def __hash__(self):
        return hash(self.id)

    def __eq__(self, other):
        return isinstance(other, MyKey) and self.id == other.id

# Usage
my_dict = {}
key1 = MyKey(1)
key2 = MyKey(1)
my_dict[key1] = 'value'
print(my_dict[key2])  # Will output 'value' because key1 and key2 are considered equal

Without the proper implementation of these methods, objects cannot be used correctly as keys.