How to Check If Key Exists In Dictionary Using Python

Last Updated on December 25, 2020 by Roshan Parihar

In this tutorial, learn how to check if the key exists in Dictionary with Python. The short answer is: use the Python for loop to iterate each element and check if the item exists.

The dictionary contains the elements with key and their associated value.

Check If Key Exists In Dictionary With For Loop in Python

You can find the given key if it exists in the given Dictionary. To perform this task, you have to use the for loop with if condition inside. The if condition finds the matching key if present in the given dictionary.

The given key is stored in the variable ‘mykey’. The for loop iterate through all the keys. After that, if the condition checks the existing key as given in the example below.

Output

The given key already exists

The above example showing 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.

How to Check If Key Exists In Dictionary Using Python

How To Check Existing Key Using Only Python If Condition

In addition to the above, you can also check the existence of the key using only if condition. If the element is present in the dictionary, the example shows the 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.

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

I hope you like this post on how to check the existence of the element in Dictionary.

Reference
Stackoverflow Discussion to Check Key Existence in DIctionary