Last Updated on May 21, 2024 by Roshan Parihar
To check if the key exists in Dictionary in Python, use the for loop to iterate through each element and check the item’s existence.
Let’s see some elements with examples given below.
Check If the Key Exists In Dictionary With For Loop in Python
If you want to check if the given key exists in the Dictionary, you have to use the for loop with if condition inside. The if condition matches the key in each iteration. When it finds the key, you will get it in the output present in the given dictionary.
Example 1
1 2 3 4 5 |
mykey = 'four'; myDict = {'one': 'Ram', 'two': 13, 'three': 'Jordge', 'four': 'Gill', 'five': 33, 'six': 'Steve'} for key, value in myDict.items(): if key == mykey: print('The given key already exists') |
Output
The above example shows that the key exists in the given dictionary. If the element does not exist in the dictionary, the above example shows element does not exist.
The given key is stored in the variable ‘mykey’. The for loop iterates through all the keys. After that, the if condition checks the existing key as given in the example above.
Find Key Existence Using Only If Condition in Python
In addition to the above, you can also check the existence of the key using only the if condition. If the element is present in the dictionary, the example shows its existence. However, if the element does not exist, it shows the element does not exist.
This process may reduce the time of executing the code. Without any iteration of the loop, it can check the existence of the element. You can prefer this method to check the element is present in the dictionary.
Example 2
1 2 3 4 5 6 |
mykey = 'four'; myNewDict = {"one": "Ram", "two": 43, "three": 10, "four": "Bilal", "five": 13.2, "six": "Feroz"} if mykey in myNewDict: print('The given key exists') else: print('Not Exists') |
Output
The above example also gives the same result as you get in the previous example. This is the easiest and fastest method of identifying the element in the dictionary.
You also like to read