Performance difference between dict.has_key and key in dict in Python

Possible duplicate:
'has_key ()' or 'in'?

There are two ways in Python to decide if there is a key in a dict :

if dict.has_key(key) and if key in dict

Someone tells me that the second is slower than the first, since the in keyword makes the expression iterate over the dict, so it will be slower than the has_key alternative, which apparently uses the hash to make the decision.

As I very much doubt the difference, since I think Python is smart enough to translate the in keyword before the dict to some hash path, I cannot find any formal statements about it.

So, is there a difference in efficiency between the two?

Thanks.

+6
source share
3 answers

Both of these operations do the same thing: consider the hash table implemented in the dict for the key. There will be no iteration of the entire dictionary. Keep in mind that for x in dict is different from if x in dict . They use the in keyword, but perform different operations.

The in keyword becomes a call to dict.__contains__ , which dict can implement, but he likes.

If there is a difference in the timings of these operations, it will be very small and will be associated with the service overlay of the has_key function.

By the way, the general preference for key in dict is a clearer expression of intent than dict.has_key(key) . Note that speed has nothing to do with preference. Readability is more important than speed if you do not know that you are on a critical path.

+8
source

D.has_key is actually slower due to a function call:

 >>> D = dict((x, y) for x, y in zip(range(1000000), range(1000000))) >>> from timeit import Timer >>> t = Timer("1700 in D", "from __main__ import D") >>> t.timeit() 0.10631704330444336 >>> t = Timer("D.has_key(1700)", "from __main__ import D") >>> t.timeit() 0.18113207817077637 
+3
source

has_key not an alternative. He is out of date. Do not use it. (However, it is slower)

+3
source

Source: https://habr.com/ru/post/919995/


All Articles