Junior — Middle
What steps must be taken for an instance of a custom class to be used as a key in a Python dictionary?
sobes.tech AI
Answer from AI
For an instance of a custom class to be used as a key in a Python dictionary, it must be hashable and comparable. To achieve this, you need to implement the __hash__() and __eq__() methods in the class. The __hash__ method should return an integer value that is unique for the object considering its significant attributes, and __eq__ should define object equality.
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 == key2
It is important that objects are immutable with respect to the attributes involved in hashing, otherwise the dictionary may not work correctly.