Sobes.tech
Junior — Middle

What are the requirements for an object to be used as a key in a dictionary?

sobes.tech AI

Answer from AI

To use an object as a key in a dictionary (dict) in Python, it must be:

  1. Hashable: the object must have a __hash__() method that returns an immutable value.
  2. Immutable: the state of the object should not change during its use as a key, otherwise the hash may change, which will break the dictionary.
  3. Comparable: the object should have a properly implemented __eq__() method so that the dictionary can compare keys.

Examples of suitable keys: numbers, strings, tuples of immutable elements.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __hash__(self):
        return hash((self.x, self.y))
    def __eq__(self, other):
        return isinstance(other, Point) and self.x == other.x and self.y == other.y

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

If the object is mutable or does not implement __hash__, it cannot be used as a key.