Python Dictionary Check if Key Exists Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Change Value in Python Dictionary?
- Python Dictionary Remove Element by Value Example
- Python Dictionary Delete Item by Key Example
- How to Remove Element from Python Dictionary?
- How to Remove Item from Dictionary in Python?
- How to Add a Key Value Pair to Dictionary in Python?
- How to Add Element in Dictionary Python?
- How to Add Item in Dictionary Python?
- Python Create JSON File from Dict Example
- How to Get Max Value from Python List?
- How to Convert List to Uppercase in Python?
- How to Convert List to Lowercase in Python?
- How to Convert List into String in Python?