Set and {} comparison confusion

Peter Otten __peter__ at web.de
Thu Sep 9 03:20:50 EDT 2004


Roman Yakovenko wrote:

> Hi. Could somebody explain why sets and dict are different ?

>>> class A(object):
...     def __eq__(self, other):
...             return True
...
>>> dict.fromkeys([A()]) == dict.fromkeys([A()])
False
>>> class B(object):
...     def __eq__(self, other):
...             return True
...     def __hash__(self):
...             return 0 # not recommended
...
>>> dict.fromkeys([B()]) == dict.fromkeys([B()])
True

For two dictionary keys to be considered as equal they must have the same
hash value. Set is implemented on top of dictionaries and therefore shows
the same behaviour.

Peter




More information about the Python-list mailing list