Possible Duplicate:
'has_key()' or 'in'?
In Python, there're two ways of deciding whether a key
is in a dict
:
if dict.has_key(key)
and if key in dict
Someone tells me that the second one is slower than the first one since the in
keyword makes the expression an iteration over the dict, so it will be slower than the has_key
alternative, which apparently uses hash to make the decision.
As I highly doubt the difference, since I think Python is smart enough to translate an in
keyword before a dict
to some hash way, I can't find any formal claim about this.
So is there really any efficiency difference between the two?
Thanks.
Note: has_key() method was removed in Python 3. Use the in operator instead.
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Parameters: There are no parameters. Returns: A view object is returned that displays all the keys.
Both of these operations do the same thing: examine the hash table implemented in the dict for the key. Neither will iterate the entire dictionary. Keep in mind that for x in dict
is different than if x in dict
. They both use the in
keyword, but are different operations.
The in
keyword becomes a call on dict.__contains__
, which dict can implement however it likes.
If there is a difference in the timings of these operations, it will be very small, and will have to do with the function call overhead of has_key
.
BTW, the general preference is for key in dict
as a clearer expression of the intent than dict.has_key(key)
. Note that speed has nothing to do with the preference. Readability is more important than speed unless you know you are in the critical path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With