How to Handle Missing Keys in Python Dictionary?

Here, we are going to learn about the different ways to handle the error which might occur due to missing keys in Python?
Submitted by Shivang Yadav, on May 27, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Dictionary is a collection in python which is used to store data as Key:value pair.

Example:

dict = { "python" : 1, "C++" : 3, "javaScript" : 2 } 

Missing Keys in Dictionary in Python

Ideally or while practicing, we will use keys of the dictionary which are present in our program. But in the real-time working of the software, there may arise a situation when either the user enters a key that is not present in the dictionary or there is a typing error from the user which may lead to runtime error due to missing keys in the dictionary. 

Python programming language provides us with the solution to this issue as it would not be practical to leave a potential error open in your program.

There are multiple ways by which we can do this in our python program. We will see each of them. 

Method 1: Using check condition and then return missing statement

In this method, we will check the input value-form users for presence in the dictionary and print the desired statement, which is the key-value pair if present or an 'error statement' when nothing is present.

# Program to handle missing key using explicit function

users = {'ram' : 'Admin' , 'john' : 'Staff' , 'nupur' : 'Manager'}

key = input("Enter the key to be searched ")

if key in users.keys(): 
    print("value : ", users[key])
else :
    print("Please enter valid key \nList of keys : ")
    for val in users.keys():
        print(val, end = " ")

Output:

Enter the key to be searched jane
Please enter valid key 
List of keys : 
john nupur ram 

This solution can do our job but there may arise a time when we don’t need to print the list and just need to return the output, the missing statement, or a default value for all missing keys. Python provides a method to perform this task, which is the get() method.

Method 2: Using Python's get method

The get() method in python operates on a dictionary and takes in the entered key and default statement. It returns the value of the key if it is present in the dictionary, otherwise printing the default statement.

Syntax:

get(search_key, default_statement)

These results are the same as above but this is a built-in function that reduces the lines of code to be written and makes the code more readable.

# Program for handling missing keys in 
# the dictionary using get() method in Python

# Crating the dictionary
users = {'ram' : 'Admin' , 'john' : 'Staff' , 'nupur' : 'Manager'}

# Getting user input for the key
key = input("Enter the key to be searched ")

# Logic to handle missing keys in dictionary 
print(users.get(key, "User key not present"))

Output:

RUN 1:
Enter the key to be searched ram
Admin

RUN 2:
Enter the key to be searched deep
User key not present

Method 3: Using setdefault() method

We can handle missing keys using the setdefault() method present in the Python library. The setdefault() method check for the presence of the key in the dictionary, if it is present in the method returns the value associated with the key and if it is not present the method will create a new key in the dictionary with the default value provided in the parameter.

Syntax:

dictionaryName.setdefault(search_key, default_value)

The method adds the seach_key with default_value to the dictionary if it is not present.

# Program for handling missing keys in 
# the dictionary using setdefault() method in python, 

# Crating the dictionary
users = {'ram' : 'Admin' , 'john' : 'Staff' , 'nupur' : 'Manager'}

# Getting user input for the key
key = input("Enter the key to be searched ")

# Logic to handle missing keys in dictionary 
print(users.setdefault(key, "User key not present"))

print("dictionary :", str(users))

Output:

RUN 1:
Enter the key to be searched ram
Admin
dictionary : {'nupur': 'Manager', 'ram': 'Admin', 'john': 'Staff'}

RUN 2:
Enter the key to be searched deep
User key not present
dictionary : {'deep': 'User key not present', 'john': 'Staff', 'nupur': 'Manager', 'ram': 'Admin'}

Method 4: Using defaultdict() method

Python's collection library has a defaultdict library container which works in the same way as a dictionary. But handles the missing key well. The defaultdict accepts the defaultValue (if none is provided it is 0). And add the missing key with the default value.

Syntax:

dictName = collections.defaultdict(lambda : 'Key Not found')
# Program for handling missing keys in 
# the dictionary using defaultdict() method in Python

import collections

# Crating the dictionary
users = collections.defaultdict(lambda : "user not present")

users['ram'] = 'Admin';
users['john'] = 'Staff';
users['nupur'] = 'Manager';

# Getting user input for the key
key = input("Enter the key to be searched ")

# Logic to handle missing keys in dictionary 
print(users[key])

Output:

RUN 1:
Enter the key to be searched ram
Admin

RUN 2:
Enter the key to be searched deep
user not present

Python Dictionary Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.