Junior — Middle
What steps are necessary to use an object as a key in a dictionary or hash table?
sobes.tech AI
Answer from AI
To use an object as a key in a dictionary (dict) or hash table in Python, it must be hashable. For this:
- The class of the object must implement the
__hash__()method, which returns an integer hash value. - The class must implement the
__eq__()method to compare objects for equality.
If these methods are properly defined and the objects are immutable, they can be used as keys.
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 = {}
points_dict[Point(1, 2)] = "A"
points_dict[Point(3, 4)] = "B"
print(points_dict[Point(1, 2)]) # Will print "A"
Thus, objects with properly implemented __hash__ and __eq__ can be used as keys in dictionaries.