Confusion about dictionaries - keys use value or identity?

Roy Smith roy at panix.com
Sun Jul 8 12:35:37 EDT 2001


I'm kind of confused about exactly what happens when I use a string as a 
dictionary key.  Section 3.2 of the reference manual seems to imply that 
keys are compared by identity:

> The only types of values not acceptable as keys are values containing 
> lists or dictionaries or other mutable types that are compared by value 
> rather than by object identity

but experimenting shows they it seems to really use value, not identity:

>>> a = 'foo'
>>> b = 'f' + 'o' + 'o'
>>> a == b
1
>>> a is b
0
>>> x = {}
>>> x[a] = 'this is a'
>>> x[b]
'this is a'

Is there a way to force the comparison to be by identity?  I'm 
contemplating building a cache (using a dictionary), and key comparison by 
identity should be significantly faster than by value, because I'm going to 
be using rather long strings as keys.



More information about the Python-list mailing list