No subject

Alex Martelli aleax at aleax.it
Wed Jul 24 04:25:43 EDT 2002


Yigal Duppen wrote:

>>> What datatypes can one use as key in a dictionary?
>> anything immutable. thats numbers, strings, tumples
> 
> And of course any object that implements the __hash__(self) method.
> 
> (Note: it is usually a good idea only to implement __hash__ for
> immutable objects; hashing mutable objects can give very... interesting
> results)

Right, BUT -- this isn't the whole picture.  Consider:

>>> class X: pass
...
>>> a=X()
>>> b=X()
>>> adic={}
>>> adic[a]=23
>>> adic[b]=45
>>> adic[a]
23
>>> adic[b]
45
>>>

See?  Instances of this do-nothing, know-nothing class X,
while of course being mutable, are also quite usable as keys
in a dictionary.  So, what gives?

Answer: X doesn't implement __eq__ (nor __cmp__).  Thus,
equality checks on X instances implicitly use 'is' (or, if
you prefer, implicitly use id(theinstance)).  So, the hash
value is also done that way:

>>> id(a)
135653148
>>> hash(a)
135653148
>>>

Keys don't have to be immutable, though most often they will
be: what matters is that a key never compares unequal to some
"previous version" of itself, and keys comparing equal also
have the same hash value.  In practice this means, EITHER
immutable OR not defining equality-comparison and thus
implicitly falling back to identity-comparison for the latter.


Alex




More information about the Python-list mailing list