How to Check If Key Exists in Dictionary in Python? – Definitive Guide

Python Dictionaries are used to store data in a key-value pair. Dictionaries are changeable and it doesn’t allow duplicate keys.

You can check if a key exists in a dictionary using dict.keys() method in Python.

In this tutorial, you’ll learn the different methods available to check if keys exist in a dictionary, and also you’ll learn how to check the keys in different use cases.

Sample Dictionary

This is the sample dictionary you’ll use in this tutorial. It contains the keys one, two, three, four.

All the keys are in lower case. This is useful for learning how to check if a key exists in the dictionary in a case-sensitive way.

mydict = {
    "one": "1",
    "two": "2",
    "three": "3",
    "four": "4",
}

There are three methods available in python to check if a key exists in the dictionary.

  • Using dictionary.keys()
  • Using If And IN
  • Using has_keys() (deprecated in Python 3)

Using Keys()

You can check if a key exists in a dictionary using the keys() method and IN operator.

The keys() method will return a list of keys available in the dictionary and IF, IN statement will check if the passed key is available in the list.

If the key exists, it returns True else, it returns False .

Code

key="one"

if key in mydict.keys():
    print("Key exists")    
else:
    print("Key does not exist")

Output

    Key exists

This is how you can check if a key exists using the dictionary.keys() method.

Using If and In

You can check if the key exists in the dictionary using IF and IN. When using the dictionary directly with IF and IN, it’ll check if the key exists in the dictionary.

If a key exists, It returns True else it returns False.

Code

key="one"

if key in mydict:
    print("Key exists") 
else:
    print("Key does not exist")

Output

    Key exists

This is how you can check if a key is available in the dictionary using the IF and IN.

Using has_key()

You can use the has_key() method to check if a key is available in a dictionary.

This is deprecated in python 3. If you are using an older version of python than python 3, then you can use this method.

You can check the python version in cmd using the below command.

import sys

print(sys.version)

Output

3.9.2 (default, Sep  4 2020, 00:03:40) [MSC v.1916 32 bit (Intel)]

Code

if mydict.has_key("One"):
    print("Key exists")
else:
    print("Key does not exist")

This tutorial uses the version Python 3. Hence, the below error is thrown as output.

Output

    ---------------------------------------------------------------------------

    AttributeError                            Traceback (most recent call last)

    <ipython-input-4-29ad973f8a0b> in <module>
    ----> 1 if mydict.has_key("One"):
          2     print("Key exists")
          3 else:
          4     print("Key does not exist")


    AttributeError: 'dict' object has no attribute 'has_key'

These are the different methods available in python to check if keys are available in the dictionary.

Now, you’ll learn about the different ways to use this.

Check If Multiple Keys Exists in Dictionary

You can check if multiple keys exist in the dictionary in one statement. You can use the all() along with the list comprehension to check if multiple or all keys exists in the dictionary.

Code

if all (key in mydict for key in ("one","two")):
    print("All Keys exists in the dictionary")
else:
    print("All doesn't exist")

Where,

  • for key in ("one","two") – Keys to check in the dictionary will be iterated
  • key in mydict – During the each iteration of the for loop, each key will be checked if it exists in the mydict
  • Then, it’ll return a list which contains True or False based on the INcheck.
  • At-last, the all() method checks the list. If it contains only True, then it means all the passed keys are available in the dictionary. If it contains at-least one False, then it returns false.

Output

    All Keys exists in the dictionary

Example 2

To check the negative scenario where all the passed keys are not available in the dictionary.

if all (key in mydict for key in ("one","two", "Five")):
    print("All Keys exists in the dictionary")
else:
    print("All Keys doesn't exist")

Output

    All Keys doesn't exist

This is how you can check if multiple keys exist in a dictionary in one statement.

Check If Key Exists in Dictionary Case Insensitive

By default, the IF, IN method is case-sensitive. When you check if a key exists in the dictionary using the IF, IN method, you should pass the proper case.

  • To check if a key exists in a dictionary in a case-insensitive way, you need to create a set by converting all the keys to either lowercase or uppercase.

Code

In the example, you’ll

  • convert all the keys to lowercase using the lower() method.
  • convert the key to be checked to lower case.
  • Pass the key to be checked and the set with lower case keys to IF, IN statement to check if a key exists in a case-insensitive way.
mydict = {
    "one": "1",
    "two": "2",
    "three": "3",
    "four": "4",
}

set_with_keys = set(key.lower() for key in mydict)

key_to_check = "One"

if key_to_check.lower() in set_with_keys:
    print("Key exists")
else:
    print("Key doesn't exists")

Output

    Key exists

This is how you can check if a key exists in a dictionary in a case-insensitive way.

s.

Check If Key Exists and Has Value

You can check if a key exists and has a specific value in the dictionary by using the dictionary.items() method.

The items() method will return a list of tuples with the available key pairs in the dictionary.

Use IF and IN with a tuple to check if it exists in the dictionary, as shown below.

Code

if ("one", "1") in mydict.items():
    print("Key and Value exists")
else:
    print("Key value pair doesn't exists")

Output

    Key and Value exists

This is how you can check if a key exists and has a value in the dictionary.

nary.

Check if Key Exists in Dictionary Time complexity

This section explains the time complexity of the different methods that checks if a key exists in a dictionary.

Time Complexity Table

OperationAverage CaseAmortized Worst Case
k in dO(1)O(n)
Get ItemO(1)O(n)
Iteration[3]O(n)O(n)

Based on the above table, using the IF and IN statements are the best and fastest way to check if a key exists in the dictionary.

Additional Resources

Leave a Comment