ItSolutionStuff.com

Python Dictionary Check if Key Exists Example

By Hardik Savani • October 30, 2023
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: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Change Value in Python Dictionary?

Read Now →

Python Dictionary Remove Element by Value Example

Read Now →

Python Dictionary Delete Item by Key Example

Read Now →

How to Remove Element from Python Dictionary?

Read Now →

How to Remove Item from Dictionary in Python?

Read Now →

How to Add a Key Value Pair to Dictionary in Python?

Read Now →

How to Add Element in Dictionary Python?

Read Now →

How to Add Item in Dictionary Python?

Read Now →

Python Create JSON File from Dict Example

Read Now →

How to Get Max Value from Python List?

Read Now →

How to Convert List to Uppercase in Python?

Read Now →

How to Convert List to Lowercase in Python?

Read Now →

How to Convert List into String in Python?

Read Now →