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

skip at pobox.com skip at pobox.com
Wed Dec 6 21:39:06 EST 2006


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

Skip



More information about the Python-list mailing list