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

Hendrik van Rooyen mail at microcorp.co.za
Thu Dec 7 02:35:28 EST 2006


 <skip at pobox.com> wrote:

>     Peter> Bjoern Schliessmann wrote:
>     >> Wouldn't be "if k in d.keys()" be the exact replacement?
>
>     Peter> No, 'k in d' is equivalent to 'd.has_key(k)', only with less
>     Peter> (constant) overhead for the function call. 'k in d.keys()' on the
>     Peter> other hand creates a list of keys which is then searched linearly
>     Peter> -- about the worst thing you can do about both speed and memory
>     Peter> footprint.
>
> I will admit that way back when (maybe 8 yrs ago) I actually did this in a
> piece of frequently executed code that's been stable for a looong time.  I
> have no idea why I might have written it that way.  Brain fart I suppose.  I
> only noticed my mistake a couple months ago during a trip into the
> containing function for some other stuff.  Man, was I embarrassed...

why? - the main point is actually that the code worked, and was stable -
that should make you proud, not embarrassed.  I think that there is far too much
emphasis on doing things the quickest way - as long as it works, and is fast
enough,
its not broken, so don't fix it...

- Hendrik




More information about the Python-list mailing list