python check if key exists in dictionary

Previous

It is very easy to check if key exists in dictionary in python.

You need to use “in” keyword to check if key exists in dictionary.

So you can just use if ‘three’ in my_dict: to check if ‘three’ string exists as key in my_dict.
Let’s understand with the help of example.

my_dict = {'John':18,'Mohan':23,'Martin':26,'Adam':40} if 'Martin' in my_dict: print("Age of employee Martin is: ",my_dict['Martin']) if 'Mary' in my_dict: print("Age of employee Mary is: ",my_dict['Mary']) else: print("Mary is not key in dictionary my_dict")

Output:

Age of employee Martin is: 26
Mary is not key in dictionary my_dict

Source:
https://docs.python.org/3/tutorial/datastructures.html
https://www.code2master.com/python/check-key-exists-dictionary-python/

That’s all about how to check if key exists in dictionary.

Previous

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog