CodexBloom - Programming Q&A Platform

Handling Key Collision in Python Dictionary with Custom Class as Key and Maintaining Insertion Order

πŸ‘€ Views: 59 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
python dictionary custom-class

I'm having trouble with I'm migrating some code and I'm facing an issue where I want to use instances of my custom class as keys in a Python dictionary..... I want to ensure that if two instances with the same attributes are used as keys, they should refer to the same entry in the dictionary, but I'm encountering unexpected behavior. I have overridden the `__eq__` and `__hash__` methods in my class, but when I try to insert two identical instances, it creates two separate entries instead of overwriting the first one. Here’s my custom class: ```python class CustomKey: def __init__(self, identifier): self.identifier = identifier def __eq__(self, other): return isinstance(other, CustomKey) and self.identifier == other.identifier def __hash__(self): return hash(self.identifier) ``` When I run this code: ```python key1 = CustomKey('123') key2 = CustomKey('123') d = {} d[key1] = "First Entry" d[key2] = "Second Entry" print(d) ``` The output is: ``` {<__main__.CustomKey object at 0x...>: 'First Entry', <__main__.CustomKey object at 0x...>: 'Second Entry'} ``` Instead of updating the existing entry for the same identifier, I see two different objects. I’ve looked into the documentation for Python 3.10, and I’m not sure if I’m missing something with respect to how dictionaries handle keys and equality. I want to maintain the insertion order as well, so I'm using a normal dictionary. How can I fix this issue to properly handle key collisions with my custom class? Any insights would be greatly appreciated! I'm developing on CentOS with Python. I'd be grateful for any help. I'm working with Python in a Docker container on Ubuntu 22.04. Could someone point me to the right documentation?