has_key() method in Python Dictionary
In this tutorial, we will discuss has_key() in Python Dictionary. As the name suggests has a key, if it has the key then it will return True otherwise false.
This is helpful in cases where we are searching for whether the key exists. Here we will use this in-built has_key()
which checks for the key existence.
Syntax of has_key()
Here is the syntax of has_key()
where mydict
is the name of the dictionary from where we need to search for the key and the key is actually the name of the key we need to search for-
dict.has_key(key)
It returns a bool value.
Implementation in Python 2
Here we have used an in-built function named has_key(key)
to check for the existence of a key.
Although this function only works well in Python 2.
mydict={"Khushi":3,"Anjali":5,"Muskan":7} print(mydict.has_key("Khushi"))
True
Implementation in Python 3
The same function is replaced by mydict.__contains__(key)
in Python 3 and is very similar to the above-mentioned has_key(key)
.
mydict={"Khushi":3,"Anjali":5,"Muskan":7} print(mydict.__contains__("Khushi"))
True
So we have discussed how to search for a key in Python 2 and Python 3 using different methods.
Leave a Reply