Python Dictionary Check if Key Exists Example

By Hardik Savani October 30, 2023 Category : Python

Hey Friends,

In this short guide, we will show you python dictionary check if key exists. we will help you to give an example of how to check if key is present or not in dictionary python. if you want to see an example of python check key in dictionary exists then you are in the right place. you will learn python check if keys exists in dictionary. So, let us dive into the details.

There are several ways to check key is exists or not in dictionary in python. i will give you two examples using if condition and using custom function in python.

So, without further ado, let's see simple examples:

Example 1:

main.py

user = {
  "ID": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}
  
# Check key is exists in dictionary
if "name" in user:
    print("'name' key is exists.")
else:
    print("'name' key is not exists.")

Output:

'name' key is exists.

Example 2:

main.py

user = {
  "ID": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}

def checkKeyExists(dic, key):
    if key in dic.keys():
        print("Present, ", end =" ")
        print("value =", dic[key])
    else:
        print("Not present")
         
# Check key is exists in dictionary
key = 'name'
checkKeyExists(user, key)
  
# Check key is exists in dictionary
key = 'demo'
checkKeyExists(user, key)

Output:

Present,  value = Hardik Savani
Not present

I hope it can help you...

Tags :
Shares