Solution:
In your code, you have used the if
and in
method.
This method simply uses if
statement to check whether the given key exists in the dictionary. I don’t why are you thinking this is not the best way to check. This is one of the most used methods.
Well, as far as you don’t like to write code in this method. I can introduce you to another way to do the same thing by using the Inbuilt method keys()
def checkKey(dict, key):
if key in dict.keys():
print("Present, ", end =" ")
print("value =", dict[key])
else:
print("Thanks")
# Driver Code
dict = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dict, key)
key = 'w'
checkKey(dict, key)
The 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.
Thanks.