How to check if key exists in a python dictionary?

In this tutorial, there will be a detailed demonstration with an example code about how you can check if a key is present in a dictionary. Dictionaries are an important data structure and part of almost everyone’s applications. the purpose of using dictionaries is to store all kinds of useful data like keys, passwords etc… However, the dictionary data structure is one of the simplest and most versatile. A dictionary is used to store any object: strings, numbers, lists and much more.

*Working on Anaconda Environment->Jupyter notebook Python version 3.0+.

What is the Purpose behind checking if a key exists in a python dictionary?

The purpose of checking if a key exists in a python dictionary is to give justice to the Pythonic syntax. However, It helps to determine whether or not the value associated with that key is present because in case the key is not present, it will the Python Script will raise a “Keyword Error”

However, use Keys and values to store key-value pairs in a dictionary. Therefore, checking if the key exists before accessing its value prevents you from dealing with a keyword error that raises when a Python script executes.

For example, you have a list of flowers, and each flower is associated with respected species. You might want to make sure that those flowers exist before you can use them in an application.

How to check if a key exists in a python dictionary?

Checking keys existence in key-values pairs in a Python dictionary can access using the following methods:

  • ACCESS THE KEYS IN THE DICTIONARY USING ‘IN’ OPERATOR
  • CHECK IF MULTIPLE KEYS EXIST IN THE DICTIONARY USING ALL() FUNCTION
  • CONDITIONAL STATEMENT TO ACCESS KEYS IN A DICTIONARY
  • USE GET() APPROACH FOR CHECKING IF A KEY EXISTS IN A PYTHON DICTIONARY
  • USE KEYS() METHOD TO ACCESS A KEY IN A PYTHON DICTIONARY
  • USE TRY-EXCEPT BLOCKS IN AGGREGATION WITH [] OPERATOR
  • USE SETDEFAULT() FUNCTION APPROACH TO CHECK KEY EXISTENCE
  • USE COUNT() FUNCTION WITH KEYS() METHOD TO CHECK KEY EXISTENCE
  • HAS_KEY() METHOD TO ACCESS THE KEY IN THE PYTHON DICTIONARY

Access the keys in the dictionary using the ‘in’ operator

In Python, if you have a dictionary with key-value pairs and want to check if a key exists, you can use thein keyword operator. 

Here is how the ‘in’ operator functioning within the script: 

The ‘in’ Operator works as a boolean function. Therefore, the code checks whether the key is present in the dictionary or not. However, the Python script returns True as an output if the key includes in the dictionary. Otherwise, it returns False. 

The below example code demonstrates how to check if a key includes in a dictionary using the in operator in Python. 

The Example code then checks if the string ‘Designation’ is key in the dictionary dict by using ‘in‘ operator. However, ‘Designation‘ is key in the dictionary, the output of the first print statement would be True.

Similarly, the Python script does with the ‘stu_name’ case

dict= {'Designation': 'Developer', 'stu_name': ['Hemsworth', 'Potter']}
print("Designation exists in dictionary:\n", 'Designation' in dict)
print("\nstu_name exists in key:\n ", 'stu_name' in dict)
Designation exists in dictionary:
 True

stu_name exists in key:
  True

Check if multiple keys exist in the dictionary using all() function

The all() function acts as a boolean function. However, the all() function checks if all the keys are present in the dictionary. Therefore, the function returns True if all the elements/items of the iterable passed to it are true, and in the else case, returns False.

The all() function checks if all the items in the for..in the structure are true. However, If they are all true, it means that keys are present in the dictionary, and the code prints the command string “Keys exists in dictionary“. Otherwise, it prints the string “No such keys exist“.

# consider a dictionary
dict = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}
if all (key in dict for key in ("Red Ginger","water lily")):
    print("Keys exists in dictionary \n")
else:
   print("No such keys exist")
Keys exists in dictionary 

Conditional statement to access keys in a dictionary 

You can use the if-else conditional statement to check if a key exists. 

The below example code demonstrates how to check if a key exists in a dictionary using the ‘in‘ operator in Python. Therefore, If the key exists, it executes an if-else conditional statement to grab the value corresponding to the respective key in a dictionary. However, If the key includes in the dictionary, the corresponding value is printed.

Here is how a conditional statement checks if a key exists in a python dictionary:

The Python script first checks on key existence using the in operator; if it exists, it qualifies for the next step and checks if the string ‘stu_name‘ is key in the dictionary dict using the in operator. However, ‘stu_name' is key in the dictionary, and the if statement gets executed. 

Within the if statement, the Python script prints a message “check Name key in dictionary:” and the value corresponding to the key ‘stu_name‘ in the dictionary dict. Therefore, the value corresponding to the key ‘stu_name‘ is ['Hemsworth', 'Potter'], the output returns as ['Hemsworth', 'Potter'].

dict= {'Desgination': 'Developer intern', 'stu_name': ['Hemsworth', 'Potter']}
if 'stu_name' in dict:
   print("check Name key in dictionary:\n", dict['stu_name'])
else:
   print("No such key is present ")
check Name key in dictionary:
 ['Hemsworth', 'Potter']

Using the get() approach for checking if a key exists in a python dictionary

The get() function helps to check if a key exists in a dictionary using the in operator in Python. 

The below example accesses the value associated with the key ‘year‘ using the get() approach, which returns the value if the key exists in the dictionary, and returns None otherwise. 

The below example checks if access_value is None; it prints the message and the associated value using the print() function. Otherwise, it prints a message that the key does not exist in the dictionary.

In the below example, However, the key ‘year' exists in the dictionary; the Python script output will be: "key: 'year' : 2023".

dict = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
        'month': ['Jan','Feb', 'Mar', 'Apr'],
        'year': '2023'}
access_value = dict.get('year')
if access_value is not None:
   print(" key: 'year' :", access_value)
else:
   print("No such key exists")
key: 'year' : 2023

You can write the above code in the following Pythonic way:

dict = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
        'month': ['Jan','Feb', 'Mar', 'Apr'],
        'year': '2023'}
key_not_exists = "No such key exists"
access_value = dict.get('year', key_not_exists)
if access_value!=key_not_exists:
   print("key: 'year' :", access_value)
else:
   print(access_value)
key: 'year' : 2023

Using the keys() method to access a key in a python dictionary

Using the keys() method to access the values of the keys in the dictionary. However, Using the keys() method is a convenient way to check if a particular key exists in a dictionary.

The below example checks if the string key ‘month‘ is in the check_keys using the in operator. However, If ‘month' does exist in the dictionary; the code prints a message that the key exists and prints the associated value using the print() function. Otherwise, it prints that the key does not exist in the dictionary.

In the below example code, the key ‘month‘ exists in the dictionary, and the print() function prints: "Key exists: ['Jan', 'Feb', 'Mar', 'Apr']".

dict = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
        'month': ['Jan','Feb', 'Mar', 'Apr'],
        'year': '2023'}
#using key() function
check_keys = dict.keys()
#check if 'month' does exists in check_keys using in operator, if qualifies proceed to if statement
if 'month' in check_keys:
   print("Key exists: \n", dict['month'])
else:
   print("No such key exists")
Key exists: 
 ['Jan', 'Feb', 'Mar', 'Apr']

Using try-except Blocks in aggregation with [] Operator

Using a try-except block handle exceptions is a common practice in Python programming and can be used to deal with errors that might occur while running your code. Moreover, It allows your program to continue running despite encountering an error and provides a way to customize the error message that displays to the user.

To handle the KeyError exception, the code uses a try-except block. However, If the try block raises a KeyError, the code executes the except block, which prints a message that the key does not exist in the dictionary.

Here is how it executes the  try-except Blocks:

The code example defines a variable called check_key with a string value of ‘date and time‘, which is not a key in the dictionary.

The Python script then attempts to access the value associated with the 'date and time' key. However,  this key does not exist in the dictionary; the code raises a KeyError. To force the Python script to continue to execute the command lines,  a try-except block introduces within the Python script. This way, the try-except block executes instead of raising the keyword Error.  However, the key ‘date and time‘ does not exist in the dictionary, the Python script executes the except command and prints the string “No such key exists“.

dict = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
        'month': ['Jan','Feb', 'Mar', 'Apr'],
        'year': '2023'}
check_key = 'date and time'
try:
   access_value = dict[check_key]
   print("Key exists: \n", access_value)
except (KeyError):
   print("No such key exists")
No such key exists

Using setdefault() function approach to check key existence

The setdefault() method takes two arguments: the first is the key to be searched, and the second is optional. 

The setdefault() method is a straightforward approach to grabbing the corresponding key value in a dictionary. However, If the key exists in the dictionary, the method returns the value of the respective key. Since, If the key doesn’t involve in the dictionary, the method executes a second argument if passed.

Here is how it executes:

  • Consider a dictionary
  • Defines a variable with a string value of ‘passion flower', the key to be searched for in the dictionary.
  • Invoke the setdefault() method to access the value associated with the key key_check in the dictionary.
  • prints the values of access_value1 and access_value2 using the print() function.

However, the key ‘passion flower‘ exists in the dictionary, the setdefault() method returns the value associated with this key, which is 3.

# consider a dictionary
dict = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}
#key to be searched within dictionary
key_check = 'passion flower'
access_value1 = dict.setdefault(key_check)
access_value2 = dict.setdefault('rose', 'No such key exists' )
print("Key exists: \n", access_value1)
print("Key exists: \n", access_value2)
Key exists: 
 3
Key exists: 
 No such key exists

Using the count() function with the keys() method to check key existence

The count() method is useful for checking if an element exists in a list. However, If the element exists, the method returns the number indicating how frequently the number is in the list. Therefore, If the element does not exist, the method returns 0.  

By checking if the count of the key in the list is equal to 1, we can determine whether the key exists in the dictionary. However, the key ‘passion flower‘ exists in the dictionary, and the output of the program will be: “Exist“.

Here is how the count() function determines if the key exists in the dictionary or not:

  • Defines a variable called key_check with a string value of ‘passion flower‘, which is a key to be searched for.
  • Now uses the keys() method to access all the keys in the dictionary and stores them in a list called access_value1.
  • The count() function Checks if the key key_check exists in the list access_value1.

 If the count is equal to 1, it means that the unique key exists in the dictionary and the value of the variable not_exist is updated to Exist“. Otherwise, the value of not_exist remains as “No such key exists“.

# consider a dictionary
dict = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}
#key to be searched within dictionary
key_check = 'passion flower'
access_value1 = list(dict.keys())
not_exist = "No such key exists"
if(access_value1.count(key_check) == 1):
   not_exist = "Exist"
print(not_exist)
Exist

has_key() method to access the key in the Python dictionary

If you are working in a Python version, below 3.0. However, then the environment supports the has_key() method. Python 2 users can use that method when checking for the key existence in Python. 

However, the syntax for has_key() will be as:

if flowers.has_key(key_check):
    print("Key exists: \n")
else:
    print("No such key exists")

For Python users 3.0 or above, the has_key() raised an AttributeError: 'dict' object has no attribute 'has_key'.

# consider a dictionary
flowers = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}
#key to be searched within dictionary
key_check = 'passion flower'
if flowers.has_key(key_check):
   print("Key exists: \n")
else:
   print("No such key exists")
AttributeError: 'dict' object has no attribute 'has_key'

Conclusion

Summing up, the article demonstrates how you can check if a key does exit in a Python dictionary or access the respective keys’ values in key-value pairs. However, there are some restrictions while answering the query as it varies based on which version of Python you’re working on. However, If you are working in Python 2.7, you can use the has_key() method, whereas Python 3 environment does not support has_key(). However, in detail, all possible ways are demonstrated with an example code.

Leave a Comment

Your email address will not be published. Required fields are marked *