PYTHON

Create Custom Hashable Objects for Dict Keys

Learn to define custom Python objects that can be used as dictionary keys or stored in sets by implementing `__eq__` and `__hash__` methods, enabling powerful custom data structures.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        # A good hash function is crucial. Using a tuple of attributes often works well.
        return hash((self.x, self.y))

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

# Create instances of the custom object
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = Point(1, 2) # Same as p1

# Use custom objects as dictionary keys
data_map = {}
data_map[p1] = "Value for P1"
data_map[p2] = "Value for P2"
data_map[p3] = "Value for P3 (should overwrite P1's value)"

print("Dictionary with custom keys:")
print(data_map)
print(f"Retrieving p1's value: {data_map[Point(1,2)]}") # New object with same values works

# Use custom objects in a set
point_set = {p1, p2, p3, Point(5,6)}
print("
Set of custom objects:")
print(point_set)

# Expected output:
# Dictionary with custom keys:
# {Point(1, 2): 'Value for P3 (should overwrite P1\'s value)', Point(3, 4): 'Value for P2'}
# Retrieving p1's value: Value for P3 (should overwrite P1\'s value)
#
# Set of custom objects:
# {Point(1, 2), Point(3, 4), Point(5, 6)}
How it works: This snippet demonstrates how to create custom Python objects that can be used as keys in dictionaries or stored in sets. For an object to be "hashable" (a requirement for dict keys and set elements), it must implement both the `__eq__` (equality) and `__hash__` methods. `__eq__` defines when two objects are considered equal, while `__hash__` returns an integer hash value. A consistent hash value for equal objects is critical for correct dictionary and set behavior. By implementing these, instances of `Point` can effectively serve as unique identifiers in hash-based collections.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs