Python: Check If Given Key Exists in A Dictionary

In this article, you will learn how to use Python to check if a given key exists in a dictionary. I’ll go over three different methods for determining whether a key exists in the dictionary.

If you’re new to Python, you might be wondering what function you’ll need to use to see if the key is already in the dictionary. However, Python has made it much easier to check for keys that already exist in the dictionary. All you have to do is use the ‘in’ operator.

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

The ‘in’ operator is the first method for determining whether or not a given key exists in the dictionary. This operator determines whether the provided key exists in the dictionary and returns true if it does, otherwise it returns false.

As a result, this operator is typically used in conjunction with an if statement because it returns a boolean expression, and we require an if statement to properly evaluate such a boolean expression. In the following example code, we will see how to use 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 code above, the key ‘C’ exists in the dictionary I created, so the if condition returns true for the key to check in the dictionary. If you change the key to a different value that is not in the dictionary, you will see the key not found printed.

Let’s run the same code as before with different inputs to get the result “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 is to wrap the code where you want the dictionary value to be set for a specific key. If the key is not found, it will throw a KeyError, which you must catch in order to print that the key was not found.

In the following example code, we will see how to use the Try and Except methods to search 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 preceding code, because the key ‘D’ is not present in the given dictionary, it throws the KeyError exception, which I caught using the except keyword and then printed that the key is not found.

Let’s see if the above code prints out the correct value if the key exists 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 accepts a key as input and returns the value of the key if it exists in the dictionary; otherwise, it returns None.

In the following example code, we will see how to use the get() method to determine whether or not a given key exists in a dictionary.

#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, implying that the key is present in the dictionary. Let’s take a look at what happens when the given key ‘D’ isn’t found 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.

As a result of ‘D’ not being present in the above-provided dictionary, the above code returns Key Not Found.

Python: Check If Given Key Exists in A Dictionary

Wrap Up

I hope you received your answer to the question of how to check if a given key already exists in a dictionary. I’ve listed three different methods for determining whether or not a key exists in the dictionary.

If you know of a better method than the one described above, please let me know and I will gladly include 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

Leave a Comment