Junior — Middle
What inheritable methodological action must be performed for a class instance to become a valid key in a data structure like a dictionary?
sobes.tech AI
Answer from AI
For a class instance to be a valid key in a Python dictionary, it must be hashable. To achieve this, you need to implement the __hash__() and __eq__() methods.
- The
__hash__()method should return an integer value used for quick key lookup. - The
__eq__()method should define the logic for comparing objects for equality.
It is important that objects considered equal (__eq__ returns True) have the same hash (__hash__).
Example:
class MyKey:
def __init__(self, id):
self.id = id
def __eq__(self, other):
if isinstance(other, MyKey):
return self.id == other.id
return False
def __hash__(self):
return hash(self.id)
# Usage
my_dict = {}
key = MyKey(10)
my_dict[key] = "value"
print(my_dict[MyKey(10)]) # Will output "value"