Python dictionary has_key() Method



The Python dictionary has_key() method is used to verify if a dictionary consists of the specified key or not. This function returns True if a given key is available in the dictionary, otherwise it returns False.

A python dictionary is a collection of keys and values. Sometimes there will be a need to verify whether a particular key is present in the dictionary or not. This is done with the help of the has_key() method.

Note: The has_key() method is only executable in Python 2.x. It is deprecated in Python 3.x. Instead, use the in operator.

Syntax

Following is the syntax of the Python dictionary has_key() method −

dict.has_key(key)

Parameters

  • key − This is the Key which needs to be searched in the dictionary.

Return Value

This method returns a Boolean value true if a given key is available in the dictionary, otherwise it returns a false.

Example

If the key passed as an argument is present in the dictionary, this method returns the boolean value True.

The following example shows the usage of Python dictionary has_key() method. Here, a dictionary 'dict' is created which contains the keys: 'Name' and 'Age'. Then the key 'Age' is passed as an argument to the has_key() method.

# creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
# returning the boolean value
print "Value : %s" %  dict.has_key('Age')

When we run above program, it produces following result −

Value : True

Example

If the key passed as an argument is not found in the current dictionary, this method returns False.

In this example given below the dictionary we have created contains the keys: 'Name' and 'Age'. Then, we are trying to find the key "Sex" which is not present in the dictionary.

# creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
# printing the result
print "Value : %s" %  dict.has_key('Sex')

While executing the above code we get the following output −

Value : False

Example

The has_key() has been deprecated in Python 3. Therefore, in operator is used to check whether the specified key is present in the dictionary or not.

dict_1 = {6: "Six", 7: "Seven", 8: "Eight"}
print("The dictionary is {}".format(dict_1))
# Returns True if the key is present in the dictionary
if 7 in dict_1: 
   print(dict_1[7])
else:
   print("{} is not present".format(7))
# Returns False if the key is not present in the dictionary
if 12 in dict_1.keys():
   print(dict_1[12])
else:
   print("{} is not present".format(12))

Following is an output of the above code −

The dictionary is {6: 'Six', 7: 'Seven', 8: 'Eight'}
Seven
12 is not present
python_dictionary.htm
Advertisements