python

Check if a key exist in a dictionary Python

To check whether a key exists in a dictionary or not you can use python has_key() method or you can also use in keyword for if statement condition.

#dictionary - user
user = {
    "name": "John",
    "email": "[email protected]"
}

#check using has_key
if user.has_key('email'):
    print("email key exists in the dictionary")
else:
    print("email key does not exist")

#check using in
if 'email' in user:
  print "email key exists"
else:
  print "email key does not exist"

In the code snippet, there is a dictionary name user which has two key-value pairs. We want to know if the user dictionary has a key email or not. We are checking this by using the has_key() method and in keyword usage.

Check Key existence using has_key() method

You can check if a key exists in a dictionary by using has_key() method. It takes the key name as a parameter. For example, if we want to check whether name key exists in the user dictionary we can use below code:

if user.has_key('name'):
    print("name key exists")
else:
    print("name key does not exist")

Check Key existence using in keyword

You can also check whether a key exists in a dictionary or not using the 'in' keyword. For example, if we want to check whether the name key exists in user dictionary or not, you can below code:

if 'name' in user:
    print("name key exists")
else:
    print("name key does not exist")
Was this helpful?