objects as mutable dictionary keys
Andrew Dalke
dalke at dalkescientific.com
Mon Dec 27 17:59:14 EST 2004
Andrew Koenig:
> If d is a dict and t1 and t2 are tuples, and t1 == t2, then d[t1] and d[t2]
> are the same element.
So long as the elements of t1 and t2 are well-behaved.
>>> class Spam:
... def __hash__(self):
... return id(self)
... def __eq__(self, other):
... return True
...
>>> t1 = (Spam(),)
>>> t2 = (Spam(),)
>>> t1 == t2
True
>>> hash(t1) == hash(t2)
False
>>> d = {t1: "T1", t2: "T2"}
>>> d[t1]
'T1'
>>> d[t2]
'T2'
>>> d[t1] == d[t2]
False
>>> d[t1] is d[t2]
False
>>>
Dictionaries have the extra requirement that if
k1 == k2 then hash(k1) == hash(k2).
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list