On 12.05.2011 15:44, Rahul Amaram wrote:
The preferred way for checking if a key (k) exists in a dictionary (d) is "if k in d". This is faster than "if k in d.keys()" and this has superseded "d.has_key(k)"
While 'k in d' is the right way to do it, I feel the claim it's faster that 'k in d.keys()' is somewhat weak. While this is technically true, it's a constant overhead, not some cost linear in the size of the collection - at least in Python 3 - because .keys() returns a view.
timeit("'1234567' in d", "d=dict((str(x),x) for x in range(5000000))") 0.09317641210044993 timeit("'1234567' in d.keys()", "d=dict((str(x),x) for x in range(5000000))") 0.1938305479460105 timeit("'1234567' in dkeys", "dkeys=dict((str(x),x) for x in range(5000000)).keys()") 0.0903750153983367
So "x in d.keys()" is slower than "x in d", but only by the cost of a method lookup. I don't see any reason ever to recommend using "x in d.keys()", but I think it's misleading to say that this is because of performance reasons, assuming that we are talking about Python 3. (I also completely agree with everything Georg said, FWIW.)