Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency difference between dict.has_key and key in dict in Python [duplicate]

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.

like image 461
Derrick Zhang Avatar asked Jul 09 '12 01:07

Derrick Zhang


People also ask

Does Python 3 have key alternative?

Note: has_key() method was removed in Python 3. Use the in operator instead.

How do you check if a key is not in a dictionary in python?

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.

How do you check if a key is in a dictionary python?

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.

What are keys in dictionary python?

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.


1 Answers

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.

like image 167
Ned Batchelder Avatar answered Nov 05 '22 18:11

Ned Batchelder