Tuesday, February 14, 2023

Missing Keys in Python Dictionary

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

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

 

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))
Source: www.includehelp.com