How to Check if a key exists in Python Dictionary

Filed Under: Python
Check If Key Exists In Python Dictionary

Hey there! Today we are going to cover the various techniques or methods to check if a given key exists in a Python Dictionary or not.

Introduction

In many cases, we may need to check the presence of a key in a dictionary before adding, accessing, or modifying one to avoid an error. For that before-hand checking, we can follow any one of the below-mentioned methods.

So without further ado, let us get started.

Ways to check if a key exists

Below, we have mentioned the five(5) of the most common and easy techniques for accomplishing the task.

  1. Using try-except code Block,
  2. the ‘in’ operator,
  3. the get() Method,
  4. keys() Method,
  5. the has_key() Method.

Now, we are going to go through each one of them one-by-one.

1. Using try-except code Block

A KeyError is raised when a key we are accessing doesn’t belong to the set of existing keys of the dictionary. We can use this fact to check for error(using exception handling) for checking if a key already exists in a dictionary.

So in the below code example, we have used a try-except code block to try accessing our dictionary element with the given key. If the key exists, no exception will be raised and the else part would be executed. Whereas if a KeyError is encountered we can clearly infer that the key does not exist.

#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

try:
    My_Dict[My_key]
except KeyError:
    print("Key doesn't exist!")
else:
    print("Key present!")

Output:

Enter the key to be searched: Kyler
Key present!

Here since 'Kyler' is a key that already exists in the dictionary My_Dict, KeyError is not raised. And hence, we get our desired output.

2. Using ‘in’ operator

The Python in operator is used for checking whether an element is present in a sequence or not. The syntax for using the same is given below.

given_key in given_dictionary

Here, the above code snippet evaluates to True if given_key is present in the sequence(for this article dictionary) given_dictionary. Or else to False if it is not.

Have a look at the example given below. It illustrates the use of the in operator on a dictionary perfectly.

#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

if My_key in My_Dict:
    print("Found!")
else:
    print("Not Found!")

Output:

Enter the key to be searched: Joy
Found!

3. Using get() Method

The get() method in Python returns the value for the given key if it is in the dictionary on which the method is applied. If the key does not exist, the default set by the user is returned.

get(key[, default])

Here, key is the key name that we are searching for.

Look at the below-given code snippet carefully.

#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

if My_Dict.get(My_key):
    print("Found!")
else:
    print("Not Found!")

Output:

Enter the key to be searched: John
Found!

From the above output it is clear that "John" is already present in the dictionary My_Dict.

4. Using keys() Method

The Python dictionary keys() method returns a new view of the dictionary’s keys. Hence, we can use this method to check if a key exists in Python Dictionary by using a combination of this method and the in operator.

Here is an example below for better understanding.

#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

if My_key in My_Dict.keys():
    print("Found!")
else:
    print("Not Found!")

Output:

Enter the key to be searched: Sneh
Not Found!

Since, the given key in this case does not belong to the set of keys present inside the dictionary, we get a negative result.

5. Using has_key() Method

The has_key() method has been omitted in Python 3.x versions and hence can be only used in older versions.

So for the older versions, we can use this method to check if a key exists in Python Dictionary. The method returns True if the passed key exists in the dictionary. Or else, returns False. Have a look at an example below.

#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = "Sona"

print(My_Dict.has_key(My_key)) #bool result

if My_Dict.has_key(My_key):
    print("Found!")
else:
    print("Not Found!")

Output:

True
Found!

We can see here that the method returns a True since the given key(“Sona“) exists.

Summing Up

That’s it for today. In this tutorial, we discussed the various methods of checking whether a given key exists in a dictionary or not. Hope you had a clear understanding.

We recommend going through our Python tutorial for more info.

For any further questions, feel free to use the comments below.

References

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages