dict.has_key(x) versus 'x in dict'

Fredrik Lundh fredrik at pythonware.com
Wed Dec 6 07:30:21 EST 2006


Paul Melis wrote:

> I've always been using the has_key() method to test if a dictionary
> contains a certain key. Recently I tried the same using 'in', e.g.
>
> d = { ... }
> if k in d:
>    ...
>
> and found that it seems to perform a lot better when lots of key-tests
> are to be performed. I also noticed that has_key() is scheduled to be
> removed from future (C)Python versions.
>
> Does the 'in' way of testing have an optimized implementation compared
> to has_key()?

no, but full method calls are a lot slower than the under-the-hood C-level
call used by the "in" operator.

this is why e.g.

    string[:len(prefix)] == prefix

is often a lot faster than

    string.startswith(prefix)

and why

    if character in string:
        string = string.replace(character, replacement)

is faster than

    string = string.replace(character, replacement)

if the character isn't there most of the time, despite the fact that the "replace"
method doesn't actually do something if the character isn't found.

</F> 






More information about the Python-list mailing list