Given a dictionary in Python, write a Python program to check whether a given key already exists in a dictionary. If present, print “Present” and the value of the key. Otherwise print “Not present”.
Examples:
Input : {'a': 100, 'b':200, 'c':300}, key = b Output : Present, value = 200 Input : {'x': 25, 'y':18, 'z':45}, key = w Output : Not present
Approach #1 : Using Inbuilt method keys()
keys()
method returns a list of all the available keys in the dictionary. With the Inbuilt method keys()
, use if statement and the ‘in’ operator to check if the key is present in the dictionary or not.
# Python3 Program to check whether a # given key already exists in a dictionary. # Function to print sum def checkKey( dict , key): if key in dict .keys(): print ( "Present, " , end = " " ) print ( "value =" , dict [key]) else : print ( "Not present" ) # Driver Code dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 } key = 'b' checkKey( dict , key) key = 'w' checkKey( dict , key) |
Output:
Present, value = 200 Not present
Approach #2 : Using if
and in
This method simply uses if
statement to check whether the given key exist in the dictionary.
# Python3 Program to check whether a # given key already exists in a dictionary. # Function to print sum def checkKey( dict , key): if key in dict : print ( "Present, " , end = " " ) print ( "value =" , dict [key]) else : print ( "Not present" ) # Driver Code dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 } key = 'b' checkKey( dict , key) key = 'w' checkKey( dict , key) |
Output:
Present, value = 200 Not present
Approach #3 : Using Inbuilt method has_key()
has_key()
method returns true if a given key is available in the dictionary, otherwise it returns a false. With the Inbuilt method has_key()
, use if statement to check if the key is present in the dictionary or not.
Note – has_keys()
method has been removed from Python3 version. Therefore, it can be used in Python2 only.
# Python3 Program to check whether a # given key already exists in a dictionary. # Function to print sum def checkKey( dict , key): if dict .has_key(key): print "Present, value =" , dict [key] else : print "Not present" # Driver Function dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 } key = 'b' checkKey( dict , key) key = 'w' checkKey( dict , key) |
Output:
Present, value = 200 Not present
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.