Confusion about dictionaries - keys use value or identity?

Tim Peters tim.one at home.com
Sun Jul 8 17:09:25 EDT 2001


[Roy Smith, contemplating dicts indexed by strings]
> ...
> Is there a way to force the comparison to be by identity?

Not short of building a wrapper object that defines __cmp__ in terms of id()
results (Paul's suggestion does that implicitly).  An extreme variant is to
pass every string thru the intern() function first (see the docs); that's
"extreme" because intern'ed strings are immortal.

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

That can't be determined without trying it both ways and measuring; the dict
and string implementations are chock full o' subtleties.

BTW, if you want, say, "aa" not to be the same key as "a"+"a", in what sense
is this dict indexed by strings?  That is, it's unclear what strings have to
do with this.





More information about the Python-list mailing list