How to Check If Key Exists In Dictionary Using Python

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

Output

The given key already exists

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.

How to Check If Key Exists In Dictionary Using Python

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

Output

The given key exists

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