How to Check If Key Exists In Dictionary Using Python

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 its 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 all, 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

Hope, you like this post of how to check the existence of the element in Dictionary. If you have any query regarding the tutorial, please comment below.

Reference
Stackoverflow Discussion to Check Key Existence in DIctionary

Also tell me, which method you are using to check if the element present in Dictionary.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.