Python | Dictionary has_key()
Last Updated :
12 Apr, 2022
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair.
Note: has_key() method was removed in Python 3. Use the in operator instead.
In Python Dictionary, has_key() method returns true if specified key is present in the dictionary, else returns false.
Syntax: dict.has_key(key)
Parameters:
- key – This is the Key to be searched in the dictionary.
Returns: Method returns true if a given key is available in the dictionary, otherwise it returns a false.
Example #1:
Python
Dictionary1 = { 'A' : 'Geeks' , 'B' : 'For' , 'C' : 'Geeks' }
print ( "Dictionary to be checked: " )
print (Dictionary1)
print (Dictionary1.has_key( 'A' ))
print (Dictionary1.has_key( 'For' ))
|
Output:
Dictionary to be checked:
{'A': 'Geeks', 'C': 'Geeks', 'B': 'For'}
True
False
Example #2:
Python
Dictionary2 = { 1 : 'Welcome' , 2 : 'To' , 3 : 'Geeks' }
print ( "Dictionary to be checked: " )
print (Dictionary2)
print (Dictionary2.has_key( 1 ))
print (Dictionary2.has_key( 'To' ))
|
Output:
Dictionary to be checked:
{1: 'Welcome', 2: 'To', 3: 'Geeks'}
True
False
Note : dict.has_key() has removed from Python 3.x
has_key() has been removed in Python 3. in operator is used to check whether a specified key is present or not in a Dictionary.
Example:
Python3
dictionary = { 1 : "Geeks" , 2 : "For" , 3 : "Geeks" }
print ( "Dictionary: {}" . format (dictionary))
if 1 in dictionary:
print (dictionary[ 1 ])
else :
print ( "{} is Absent" . format ( 1 ))
if 5 in dictionary.keys():
print (dictionary[ 5 ])
else :
print ( "{} is Absent" . format ( 5 ))
|
Output:
Dictionary: {1:"Geeks",2:"For",3:"Geeks"}
Geeks
5 is Absent
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...