Python: Check If Given Key Exists in A Dictionary

In this article, you will learn how to check if the given key Exists in a Dictionary using Python. I will discuss three different methods that you can use to check the key that exists in the dictionary.

If you are new to Python then you might be thinking what is the function that I need to use to check if the key is present in the dictionary already or not.

But checking the key that already exists in the dictionary has been made a lot easier in Python. All you are required is to use the ‘in’ operator.

1. Using ‘in’ Operator to Check If Key Exists in Dictionary

The first method by which you can check if the given key is present in the dictionary or not is the ‘in’ operator. This operator checks if the provided key is present in the dictionary and it returns true if the key is present else it returns false.

Hence this operator is usually used with an if statement since it returns the boolean expression and we need them if statement to properly evaluate such boolean expression. Let us see in the below example code the usage of the ‘in’ operator to check the keys in a dictionary.

#Initializing the Dictionary
givenDict = {'A':1, 'B':2, 'C':3}

#Checking if 'C' is present in the Dict
#Or Not
checkKey = 'C'

if checkKey in givenDict:
    print("Given {} key is present in the Dict.".format(checkKey))
else:
    print("Key not Found.")

Output:

Given C key is present in the Dict.

As you can see in the above code, the key ‘C’ is present in the dictionary I have created, and hence the if condition returns true for the key to check in the dictionary. If you will change the key to some different value that is not present in the dictionary then you will see that the key not found is printed.

Let us see the same above code with different input to get the output as key not found.

#Initializing the Dictionary
givenDict = {'A':1, 'B':2, 'C':3}

#Checking if 'D' is present in the Dict
#Or Not
checkKey = 'D'

if checkKey in givenDict:
    print("Given {} key is present in the Dict.".format(checkKey))
else:
    print("Key not Found.")

Output:

Key not Found.

2. Using Try and Except Method to Check If Key Exists in Dictionary

The second method that you can use is to wrap the code where you want the dictionary value to set for a given key. If the key will not be found then it will throw a KeyError and you need to catch this KeyError to print that the key is not found.

Let us see in the below example code the usage of the Try and Except method to check for keys in a given dictionary.

#Initializing the Dictionary
givenDict = {'A':1, 'B':2, 'C':3}

#Checking if 'D' is present in the Dict
#Or Not
try:
    getValue = givenDict['D']
except KeyError:
    print("Key Not Found.")

Output:

Key Not Found.

As you can see in the above code, as the key ‘D’ is not present in the given dictionary hence it throws the KeyError exception that I caught using the except keyword and then I printed out that the key is not found. Now let us see if the above code prints out the value correctly if the key is present in the Dictionary.

#Initializing the Dictionary
givenDict = {'A':1, 'B':2, 'C':3}

#Checking if 'C' is present in the Dict
#Or Not
try:
    getValue = givenDict['C']
    print("The given {} key is Present with value {} in Dictionary.".format('C', getValue))
except KeyError:
    print("Key Not Found.")

Output:

The given C key is Present with value 3 in Dictionary.

3. Using get Method to check if Key exists in Dictionary

The dictionary class in Python has a method or function named get[1]. This method takes a key as input and returns the value of the key if it is present in the dictionary else it returns the None.

Let us see in the below example code the usage of get() method to check if the given key exists in a dictionary or not.

#Initializing the Dictionary
givenDict = {'A':1, 'B':2, 'C':3}

#Checking if 'C' is present in the Dict
#Or Not
getValue = givenDict.get('C')

if getValue:
    print("The given {} key is Present with value {} in Dictionary.".format('C', getValue))
else:
    print("Key Not Found.")

Output:

The given C key is Present with value 3 in Dictionary.

As you can see in the above code it returns the value of the key ‘C’ from the dictionary and hence key is present in the dictionary can be assumed. Now let us see what about code prints out when the given key ‘D’ is not present in the Dictionary.

#Initializing the Dictionary
givenDict = {'A':1, 'B':2, 'C':3}

#Checking if 'D' is present in the Dict
#Or Not
getValue = givenDict.get('D')

if getValue:
    print("The given {} key is Present with value {} in Dictionary.".format('C', getValue))
else:
    print("Key Not Found.")

Output:

Key Not Found.

So, ‘D’ is not present in the above-provided dictionary hence the above code outputs Key not Found.

Python: Check If Given Key Exists in A Dictionary

Wrap Up

I hope you got your answer related to how to check if a given key already exists in a dictionary. I have listed down three different methods that you can use to check if the key is present in the dictionary or not.

Let me know if you know any better method than the one discussed above, I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. Code Examples: Multiply In Python
  2. How To Join Words In a List Using Python Code Example
  3. Python Code Example: How To Find Element in a List in 6 Way
  4. How To Iterate Over Rows in a DataFrame in Pandas Python
  5. Python Get Filename From A Path Without Extension 4 Ways
  6. How To Concatenate String and Integer In Python
  7. Code Example: Convert a String to DateTime in Python
  8. How Do I Sort A Dictionary By Value In Python
  9. Code Example: How To Add Numbers In A List Python
  10. Python – How To Delete All Files In A Directory
Python: Check If Given Key Exists in A Dictionary

Leave a Comment