Python: Check if Key Exists in Dictionary

Python: Check if Key Exists in Dictionary

Introduction

Dictionary (also known as 'map', 'hash' or 'associative array') is a built-in Python container that stores elements as a key-value pair.

Just like other containers have numeric indexing, here we use keys as indexes. Keys can be numeric or string values. However, no mutable sequence or object can be used as a key, like a list.

In this article, we'll take a look at how to check if a key exists in a dictionary in Python.

In the examples, we'll be using this fruits_dict dictionary:

fruits_dict = dict(apple= 1, mango= 3, banana= 4)
{'apple': 1, 'banana': 4, 'mango': 3}

Check if Key Exists using in Operator

The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value.

Here it will either evaluate to True if the key exists or to False if it doesn't:

key = 'orange'

if key in fruits_dict:
    print('Key Found')
else:
    print('Key not found')

Now, since we don't have an orange in our dictionary, this is the result:

Key not found

This is the intended and preferred approach by most developers. Under the hood, it uses the __contains__() function to check if a given key is in a dictionary or not.

Check if Key Exists using get()

The get() function accepts a key, and an optional value to be returned if the key isn't found. By default, this optional value is None. We can try getting a key, and if the returned value is None, that means it's not present in the dictionary:

key = 'orange'

if fruits_dict.get(key) == None:
    print('Key not found')
else:
    print('Key found') 

This results in:

Key not found

Check if Key Exists using keys()

The keys() function returns the keys from our dictionary as a sequence:

fruits_dict.keys()

This sequence contains:

dict_keys(['apple', 'mango', 'banana'])

Using this sequence, we can check if the key is present. You can do this through a loop, or better yet, use the in operator:

key = 'orange'

if key in fruits_dict.keys():
    print('Key found')
else:
    print('Key not found')

This also results in:

Key not found

Check if Key Exists using has_key()

Instead of manually getting the keys and running a check if the value we're searching for is present, we can use the short-hand has_key() function:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

key = 'orange'

if fruits_dict.has_key(key):
    print('Key found')
else:
    print('Key not found')

It returns True or False, based on the presence of the key. This code outputs:

Key not found

Handling 'KeyError' Exception

An interesting way to avoid problems with a non-existing key or in other words to check if a key exists in our dictionary or not is to use the try and except clause to handle the KeyError exception.

The following exception is raised whenever our program fails to locate the respective key in the dictionary.

It is a simple, elegant, and fast way to handle key searching:

try:
    fruits_dict[key]
except KeyError as err:
    print('Key not found')

This approach, although it may sound unintuitive, is actually significantly faster than some other approaches we've covered so far.

Note: Please note, exceptions shouldn't be used to alter code flow or to implement logic. They fire really fast, but recovering from them is really slow. This approach shouldn't be favored over other approaches, when possible.

Let's compare the performance of them to get a better idea of how fast they can execute.

Performance Comparison

import timeit

code_setup = """
key = 'orange'
fruits_dict = dict(apple= 1, mango= 3, banana= 4)
"""

code_1 = """
if key in fruits_dict:
  # print('Key Found')
  pass
else:
  # print('Key not found')
  pass 
"""

code_2 = """
if fruits_dict.get(key):
  # print('Key found')
  pass
else:
  # print('Key not found')
  pass 
"""

code_3 = """
if fruits_dict.__contains__(key):
  # print('Key found')
  pass
else:
  # print('Key not found')
  pass  
"""

code_4 = """
try:
  # fruits_dict[key]
  pass
except KeyError as err:
  # print('Key not found')
  pass 
"""
  
code_5 = """
if key in fruits_dict.keys():
  # print('Key found')
  pass
else:
  # print('Key not found')
  pass 
"""

print('Time of code_1: ', timeit.timeit(setup = code_setup , stmt= code_1, number= 10000000))
print('Time of code_2: ', timeit.timeit(setup = code_setup , stmt= code_2, number= 10000000))
print('Time of code_3: ', timeit.timeit(setup = code_setup , stmt= code_3, number= 10000000))
print('Time of code_4: ', timeit.timeit(setup = code_setup , stmt= code_4, number= 10000000))
print('Time of code_5: ', timeit.timeit(setup = code_setup , stmt= code_5, number= 10000000))

This outputs:

Time of code_1:  0.2753713619995324
Time of code_2:  0.8163219139996727
Time of code_3:  0.5563563220002834
Time of code_4:  0.1561058730003424
Time of code_5:  0.7869278369998938

The most popular choice and approach, of using the in operator is fairly fast, and it's also the intended approach for solving this problem.

Conclusion

In this article, we discussed multiple ways to check if a key exists in our dictionary or not. Then we made a performance comparison.

Last Updated: December 10th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Better understand your data with visualizations

    With over 330+ pages, you'll learn the ins and outs of visualizing data in Python with popular libraries like Matplotlib, Seaborn, Bokeh, and more.

    © 2013-2021 Stack Abuse. All rights reserved.