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 the If statement and dict.keys() method.

You may need to check if a key is present in a dictionary before adding a new key-value pair to the dictionary. In this tutorial, you’ll learn the different methods to check if a key exists in the dictionary.

If You’re in Hurry…

You can use the below code snippet to check if a key exists in the dictionary.

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

key="one"

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

Output

    Key exists

If You Want to Understand Details, Read on…

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.

The methods demonstrated in this tutorial also answers the question of how to check if Key exists in the Ordered Dictionary.

Now, let’s start.

Sample Dictionary

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

Note: all the keys are in the lower case. This is useful to learn how to check if a key exists in the dictionary in a case-sensitive way.

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

Check If Key Exists in Dictionary

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 .

Snippet

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.

Snippet

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)]

Snippet

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 Key and Value Exists in Dictionary python

You can check if key and value exist in the dictionary using the dict.items().

The items() returns a key-value pair available in the dictionary as tuples in the list.

You can pass the key-value pair as a tuple in IF statement shown below to check if the pair exists in the dictionary.

Note: This is case-sensitive. Hence pass the Key value pair in a case-sensitive way.

Snippet

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

Where,

  • ("one", "1") – Key value pair to be checked
  • mydict.items() – Dictionary items() method which will yield key value pairs as tuples.

If the key-value pair exists, then the IF statement will be executed. If it doesn’t exist, then the Else statement will be executed.

Output

    Key and Value exists

Snippet 2

Pass a key-value pair that doesn’t exist in the dictionary. Then you’ll see the Else statement executed as shown below.

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

Output

    Key value pair doesn't exists

This is how you can check if a Key value pair is available in the dictionary.

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.

Snippet

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

Snippet 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 IF, IN method, you should pass the proper case.

You can check if a key exists in a dictionary in a case insensitive way, then you need to create a set by converting all the keys to either lower case or upper case.

In the example, you’ll convert all the keys to lower case using lower() method. Then, you’ll also convert the key to be checked to lower case.

Then you can 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.

Snippet

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")

Where,

  • set(key.lower() for key in mydict) – Creating a set with all keys in lower case
  • key_to_check.lower() – Converting key to be checked to lower case
  • if key_to_check.lower() in set_with_keys: – Checking if key exists in a case insensitive way

When you execute the below code, you’ll see the below output.

Output

    Key exists

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

Check If Key Exists in List of Dictionaries

A list of dictionaries are dictionaries that are available in a list.

You can check if a key exists in the list of dictionaries by using the any() method and list comprehension available in python.

Snippet

list_of_dict = [{"one": "1"}, {"two": "2"}, {"three": "3"}]

if any("one" in keys for keys in list_of_dict):
    print("Key exists in List of Dictionary")
else:
    print("Key doesn't exists in List of Dictionary")

Where,

  • list_of_dict – list that contains three dictionary objects
  • "one" in keys for keys in list_of_dict – using list comprehension and generating the list of keys in the list of dictionaries. Then checking if one is available in the list. It’ll return a list which contains True where the key is one and False where the key is not one.
  • any() – Checks the list of True or False returned by list comprehension. If it contains at-least one True, the key one is available in the list of dictionary. Then it returns True and executes the IF block. Otherwise, it executes the Else block.

Output

    Key exists in List of Dictionary

Snippet 2

To demonstrate the unavailable key check in the list of dictionaries.

list_of_dict = [{"one": "1"}, {"two": "2"}, {"three": "3"}]

if any("five" in keys for keys in list_of_dict):
    print("Key exists in List of Dictionary")
else:
    print("Key doesn't exists in List of Dictionary")

Output

    Key doesn't exists in List of Dictionary

This is how you can check if a key exists in the list of dictionaries.

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. Then you can use IF and IN with a tuple to check if it exists in the dictionary as shown below.

If the key-value pair is exactly available in the list of tuples, then the IF block will be executed. Otherwise, Else block will be executed.

Snippet

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.

Check If Key Exists in JSON Dictionary

JSON string means Javascript Object Notation and it is stores values in a key-value pair.

You can create a dictionary using the JSON string using the json.loads() method.

Then you can normally use the IF and IN to check if the key exists in the JSON dictionary as shown below.

Snippet

json_str = """{"one": 1, "two": 2, "three": 3}"""

jsn_dict = json.loads(json_str)

if "three" in jsn_dict:
    print("Key exists in JSON Dict")
else:
    print("Key does not exist in JSON Dict")

Output

    Key exists in JSON Dict

Snippet 2

This is to demonstrate the checking existence of the non-existent key.

json_str = """{"one": 1, "two": 2, "three": 3}"""

jsn_dict = json.loads(json_str)

if "five" in jsn_dict:
    print("Key exists in JSON Dict")
else:
    print("Key does not exist in JSON Dict")

Output

    Key does not exist in JSON Dict

This is how you can check if a key exists in the JSON dictionary.

Check if Key Exists in Dictionary Time complexity

You’ve seen different methods available to check if a key exists in the dictionary. Now, you’ll learn about the time complexity of using the different methods available to check if a key exists in the 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.

To know more about the time complexity of the dictionaries, refer to this link and scroll down to the end to see about the dictionary.

Conclusion

To summarize, you’ve learned the methods available to check if the key is available in the dictionary. You’ve also learned how to use those methods in different scenarios to check if the key is available in the dictionary. Additionally, you’ve also seen the time complexity of using each method.

If you have any questions, comment below.

You May Also Like

Leave a Comment