[Python-Dev] Equal but different keys in dicts

Michael Chermside mcherm at mcherm.com
Sun Jul 11 05:06:12 CEST 2004

Suppose you create two objects which are, in fact, different, but which are ==
to each other.

>>> class AllEqual:
...     def __init__(self, name):
...         self.name = name
...     def __repr__(self):
...         return self.name
...     def __eq__(self, other):
...         return 1
...     def __hash__(self)
...         return 47
>>> a = AllEqual('a')
>>> b = AllEqual('b')
>>> a == b

Now use one as a key in a dict, then try re-setting that value:

>>> map = {a:'one'}
>>> map
{a: 'one'}
>>> map[b] = 'two'
>>> map
{a: 'two'}

That last line could just as well have read "{b: 'two'}", but the implementation
of dict keeps the ORIGINAL key rather than using the NEW key. This is the
behavior of both CPython and Jython.

My question is this: is this behavior intentional, or is it an "implementation
detail"? If intentional, is there a reason for the choice, or is it just that
one or the other behavior needed to be chosen?

[PS: I'm hoping that a good answer to this question will allow me to close bug

-- Michael Chermside

More information about the Python-Dev mailing list