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.
Output:
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:
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.
Output:
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:
The method adds the seach_key with default_value to the dictionary if it is not present.
Output:
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:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer