Confusion about dictionaries - keys use value or identity?

Paul Prescod paulp at ActiveState.com
Sun Jul 8 19:14:57 CEST 2001


Roy Smith wrote:
> 
> 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

That is confusing! It is saying that the types of objects that case
problems are those that 

 a) are mutable

AND

 b) are compared by value rather than by object identity

>..
> Is there a way to force the comparison to be by identity?  

Not on strings!

> 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.

Here's one way:

>>> class a:
...     def __init__(self, val):
...         self.val = val
...
>>> key1 = a("abc")
>>> key2 = a("a"+"b"+"c")
>>> dict={key1:5, key2:6}
>>> dict[key1]
5
>>> dict[key2]
6
>>> key1.val == key2.val
1
>>> key1 == key2
0

-- 
Take a recipe. Leave a recipe.  
Python Cookbook!  http://www.ActiveState.com/pythoncookbook




More information about the Python-list mailing list