python check if key exists in dictionary

In this post, we will see if key exists in dictionary or not.

It is very easy to check if dict has key or not.
You can simply use “in” to check if key exists in dictionary or not.

Let’s go through some example:

my_dict = {'name':'John','age':'26','sex':'male'} print("Dictionary:",my_dict) if('age' in my_dict): print("Key 'age' exists in my_dict") else: print("Key 'age' does not exist in my_dict") if('address' in my_dict): print("Key 'address' exists in my_dict") else: print("Key 'address' does not exist in my_dict")

Output:

Dictionary: {‘name’: ‘John’, ‘age’: ’26’, ‘sex’: ‘male’}
Key ‘age’ exists in my_dict
Key ‘address’ does not exist in my_dict

That’s all about Check if key exists in dictionary in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *