Computer >> Computer tutorials >  >> Programming >> Python

Python - Dictionary has_key()


When using a python dictionary, we face a situation to find out whether a given key exists in the dictionary or not. As a dictionary is an unordered list of elements, we can not find the value using position of the element. So python standard library gives us a method called has_key() which can help us in finding the existence of the key in a dictionary. This method is available only in python 2.x and not it python 3.x

Syntax

Below is the syntax of the has_key() method.

dict.has_key(KeyVal)
Where KeyVal is the value of the key to be searched.
The result is returned as True or False.

Using Numeric Key

In case we have numbers as keys we can directly use the numeric value in the has_key().

Example

Dict= { 1: 'python', 2: 'programming', 3: 'language' }
print("Given Dictionary : ")
print(Dict)
#has_key()
print(Dict.has_key(1))
print(Dict.has_key(2))
print(Dict.has_key('python'))

Running the above code gives us the following result −

Given Dictionary :
{1: 'python', 2: 'programming', 3: 'language'}
True
True
False

Using Strings as Key

In case we have strings as keys we can directly use the string value with quotes in the has_key().

Example

Dict= { 'A': 'Work', 'B': 'From', 'C': 'Home' }
print("Given Dictionary : ")
print(Dict)
#has_key()
print(Dict.has_key('From'))
print(Dict.has_key('A'))

Running the above code gives us the following result −

Given Dictionary :
{'A': 'Work', 'C': 'Home', 'B': 'From'}
False
True