How to Check if a Key Exists in a Python Dictionary?

  • Summary: To check whether a key exists in a dictionary, you can use:
    • The in keyword
    • The keys() method
    • The get() method
    • The has_key() method

Overview

Mastering dictionaries is one of the things that differentiates the expert coders from the intermediate coders. Why? Because dictionaries in Python have many excellent properties in terms of runtimeβ€”and they’re very easy to use and understand. You cannot write effective code in Python without leveraging this powerful data structure. So, let’s dive into the mission-critical question:

Problem: Given a dictionary in Python; how to check if a specific key exists within the dictionary?

device = {
 "brand": "Apple",
 "model": "iPhone 11",
}
# <Some Method to Check if the keys "brand" and "year" exists in the dictionary or not>

While working with dictionaries, you will often come across scenarios where you have to extract a certain key-value from the dictionary. However, what if the key that you want to access is not present within the dictionary? This is what happens when you do so:

Hence, it is always a good practice to check if a key exists in the dictionary or not before extracting the value. So, without further delay, let us dive into the methods used to check the existence of a key in a dictionary: 

?Method 1: Using The in Keyword

in is a keyword in Python which has two primary uses:

  • It is used to verify if a given value is present in a sequence (dictionary, string, tuple, list, etc.)
  • It can be used in a for loop to iterate through the items of a sequence.

Example:

li = [1,2,3,4,5]
# Use 1: check if "1" is present in the list
print(1 in li)
# Use 2: iterate through items in li
for i in li:
    print(i, end=" ")

Output:

True
1 2 3 4 5 

? Thus, you can use the in keyword within the if-else statements to check if a key is already present in the given dictionary.

Example:

device = {
    "brand": "Apple",
    "model": "iPhone 11",
    "year": 2018
}
if "year" in device:
    print("key year is present!")
else:
    print("key year is not Present!")
if "color" in device:
    print("key color is present!")
else:
    print("key color is not present!")

Output:

key year is present!
key color is not present!

?Method 2: Using The keys() Method

keys() is an inbuilt method in Python that extracts the keys present in a dictionary and stores them in a list. It returns a view object that contains the keys of the dictionary in a list.

Syntax: dictionary.keys()

Example:

car = {
  "Name": "Sam",
  "ID": "1094786",
  "DOB": "21-08-1964"
}
x = car.keys()
print(x)

Output:

dict_keys(['Name', 'ID', 'DOB'])

? Thus, with the help of the keys() method and the if-else statements, you can determine if a key is present in the dictionary.

Example:

device = {
    "brand": "Apple",
    "model": "iPhone 11",
    "year": 2018
}
if "year" in device.keys():
    print("key -> 'year' is Present!")
else:
    print("key -> 'year' is Not Present!")
if "color" in device.keys():
    print("key -> 'color' is Present!")
else:
    print("key -> 'color' is Not Present!")

Output:

key -> 'year' is Present!
key -> 'color' is Not Present!

?Method 3: Using get() Method

The dictionary method – get() is used to return the value of an item with the specified key.

Syntax: dictionary.get(keyname, value)

Thus you can leverage the power of the get() method in your code and check if the key is present or not.

device = {
    "brand": "Apple",
    "model": "iPhone 11",
    "year": 2018
}
if not device.get("year"):
    print("key->'year' is Absent!")
else:
    print("key year is Present!")
if not device.get("color"):
    print("key->'color' is Absent!")
else:
    print("key->'color' is Present!")

Output:

key year is Present!
key->'color' is Absent!

Explanation: In the above example the key “year” was present in the dictionary. Hence the else statement was executed. However when the next condition was evaluated, Python found that the key “color” was not present wthin the dictionary as it was unable to fetch the intended key with the help of the get() method. Hence, the if statement was executed.

✏️Note: The not keyword is a logical operator in Python that returns True if the statement/condition is true, otherwise it returns False.

?Method 4: Using has_key() Function

If you are using Python 2.x then you might fancy your chances with the has_key() method which is an inbuilt method in Python that returns true if the specified key is present in the dictionary else it returns false.

β›”Caution: has_key() has been removed from Python 3 and also lags behind the in keyword while checking for the presence of keys in a dictionary in terms of performance. So you must use avoid using it if you are using Python 3 or above.

Now let us have a look at the following program to understand how we can use the has_key() method:

device = {
    "brand": "Apple",
    "model": "iPhone 11",
    "year": 2018
}
if device.has_key("year"):
    print("key->'year' is present!")
else:
    print("key->'year' is not Present!")
if device.has_key("color"):
    print("key->'color' is present!")
else:
    print("key->'color' is not present!")

Output:

key->'year' is present!
key->'color' is not present!

Conclusion

In this tutorial, you learned about numerous methods that can be used to check if a specific key exists in a dictionary. I hope this article helped you and answered all your queries. Please subscribe and stay tuned for more interesting articles. 

Here’s a list of related articles that are highly recommended if you want to master dictionaries in Python:


The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!