[Tutor] Performance difference, ``in'' vs ``has_key()''

Andreas Kostyrka andreas at kostyrka.org
Mon Jul 18 01:48:47 CEST 2005


Am Montag, den 18.07.2005, 00:53 +0200 schrieb Max Noel:
> On Jul 17, 2005, at 20:18, Bill Campbell wrote:
> 
> > Is there any significant performance difference between the
> > tests, ``key in dictionary'' and ``dictionary.has_key(key)''?
> > I would prefer using the ``key in'' because it's a bit easier to
> > type, and can also be used with lists in addition to dictionaries.
> 
>      While we're on that topic, is there a particular reason why  
> 'in', in a dict context, searches the keys instead of doing the  
> logical thing and searching the values?

Well, sorry I consider key in dict to be more natural than value in
dict.

Actually, there are implementation aspects: key in dict is a hash
lookup. value in dict is a slow iteration over an unsorted "list".

The only way to have a quick value lookup in a dict is keeping a shadow
dictionary with inverted keys and values. (And if it's not a bijective
relationship you probably need value -> list of keys)

Andreas
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20050718/f2ee43e8/attachment.pgp


More information about the Tutor mailing list