Confusion about dictionaries - keys use value or identity?

Steve Holden sholden at holdenweb.com
Sun Jul 8 16:27:08 EDT 2001


"Roy Smith" <roy at panix.com> wrote in message
news:roy-58C72C.12353708072001 at news1.panix.com...
> 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.

Paul Prescod has given you an answer to most of your post. As far as using
strings goes, unless they are all the same legnth and al have the same
leading characters the comparison might not be as slow asyou think (although
it clearly won't be as fast as identity). Key comparison of strings will
test the lengths fisrt, and if the lengths are the same will stop once two
unequal characters are found...

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list