Should I use ‘has_key()’ or ‘in’ on Python dicts?
Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets.
Unlike sequences, which are iterables that support accessing of elements using integer indexing, dictionaries are indexed by keys. Dictionaries are generally optimized to retrieve values when the key is known. Values (definitions) mapped to a specific key (words) are similar to that of a dictionary in the real world.
This method takes in a key of the dictionary which is to be searched as a parameter and returns a Boolean value, True if the given key is present in the dictionary, else it returns False.
The in operator also does the same task as the has_key() method, not only it checks the presence of a dictionary key but also checks the presence of any value in a sequence. It also returns a Boolean value similar to the has_key() method.
Now that we have learnt how has_key() and in works, The question here is, which one is to be used while operating Python dictionaries.
When talking about Python 3, we have to note that the has_key() method has been removed, so we’ll definitely have to use the in operator. Now talking about Python 2, the use of in operator is more efficient and more Pythonic, i.e the performance of in operator is comparably high.
Also in the Python official documentation, the below statement has been mentioned.
‘has_key() is deprecated in favor of key in d’