Python Dictionary has_key() Method

Python provides the dictionary type in order to store key and value pairs. The key is used to identify the value part which is very similar to the real-life dictionary. The key is used to search, find and match specific data and return its value. The dictionary data type provides the has_key() method in order to check if the specified key exists.

has_key() Method Syntax

The has_key() method is provided in Python2 and can not be used in Python3. The has_key() method has the following syntax.

DICTIONARY.has_key(KEY)
  • DICTIONARY is the dictionary where the KEY is checked for. This is required.
  • KEY is the key we want to check in DICTIONARY. This parameter is required.

If the specified key exist int the dictionary the has_key() method returns True if not it returns False.

Check Specified Key Exist In Dictionary

The has_key() method can be used to check if the specified key exist in the specified dictionary. The has_key() method only available for the Pyhon2.

names = {'1':'─░smail' , '2':'Ahmet' , '3':'Ali'}

print(names.has_key('1'))

print(names.has_key('5'))
True
False

If you try to use has_key() method in Python3 you will get an error like below. Simply it express that the dict object to not contains ‘has_key()’ method.

AttributeError: 'dict' object has no attribute 'has_key'

has_key() Method Alternative In Python3

As Python version 3 the has_key() method is not supported. If you try to use we will get an error which is described error. But Python 3 provides more elegant and pythonic way in order to check if the specified key exist in a dictionary. The in operator can be used to in order to check a key existince in a dictionary. In the following example we will check if the key ‘1’ exist in the dictionary named names.

names = {'1':'─░smail' , '2':'Ahmet' , '3':'Ali'}

print('1' in names)

print('5' in names)

If the specified key exist the check returns True and if not returns False.

True
False

Leave a Comment