Handling missing keys in Python dictionaries
Last Updated :
22 Aug, 2023
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn’t know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys.
Handling Missing Keys in Python Dictionaries
In the example, no key named ‘c’ in the dictionary popped a runtime error. To avoid such conditions, and to make the aware user that a particular key is absent or to pop a default message in that place, there are several methods to handle missing keys.
Python3
d = { 'a' : 1 , 'b' : 2 }
print ( "The value associated with 'c' is : " )
print (d[ 'c' ])
|
Error :
Traceback (most recent call last):
File "46a9aac96614587f5b794e451a8f4f5f.py", line 9, in
print (d['c'])
KeyError: 'c'
Handling Missing Keys in Python Dictionaries
There are the methods to handle missing keys in Python Dictionaries.
Python Program to Handling Missing keys in Python Dictionaries Using key
It is the basic way to solve key errors using if-else condition. To check if the key is present or not.
Python3
ele = { 'a' : 5 , 'c' : 8 , 'e' : 2 }
if "q" in ele:
print (ele[ "d" ])
else :
print ( "Key not found" )
|
Python Program to Handling Missing keys in Dictionaries Using get()
get(key,def_val) method is useful when we have to check for the key. If the key is present, the value associated with the key is printed, else the def_value passed in arguments is returned.
Python3
country_code = { 'India' : '0091' ,
'Australia' : '0025' ,
'Nepal' : '00977' }
print (country_code.get( 'India' , 'Not Found' ))
print (country_code.get( 'Japan' , 'Not Found' ))
|
Handling Missing keys in Python Dictionaries Using setdefault()
setdefault(key, def_value) works in a similar way as to get(), but the difference is that each time a key is absent, a new key is created with the def_value associated with the key passed in arguments. In this example, we are using setdefault() function to handle the missing keys.
Python3
country_code = { 'India' : '0091' ,
'Australia' : '0025' ,
'Nepal' : '00977' }
country_code.setdefault( 'Japan' , 'Not Present' )
print (country_code[ 'India' ])
print (country_code[ 'Japan' ])
|
Python Program to Handling Missing keys in Python Dictionaries Using defaultdict
“defaultdict” is a container that is defined in a module named “collections“. It takes a function(default factory) as its argument. By default, the default factory is set to “int” i.e 0. If a key is not present in the defaultdict, the default factory value is returned and displayed. It has advantages over get() or setdefault().
- A default value is set at the declaration. There is no need to invoke the function again and again and pass the similar values as arguments. Hence saving time.
- The implementation of defaultdict is faster than get() or setdefault().
In this example, we are using defaultdict to check if the key is present or not and set default value “key not found” to the absent keys by using lambda.
Python3
import collections
defd = collections.defaultdict( lambda : 'Key Not found' )
defd[ 'a' ] = 1
defd[ 'b' ] = 2
print ( "The value associated with 'a' is : " ,end = "")
print (defd[ 'a' ])
print ( "The value associated with 'c' is : " ,end = "")
print (defd[ 'c' ])
|
Output
The value associated with 'a' is : 1
The value associated with 'c' is : Key Not found
Handling Missing keys in Python Dictionaries Using the try-except block
This program shows how to handle missing keys in Python dictionaries using a try-except block. In this example, we are using try-except block to check whether the key is present or not.
Python3
country_code = { 'India' : '0091' ,
'Australia' : '0025' ,
'Nepal' : '00977' }
try :
print (country_code[ 'India' ])
print (country_code[ 'USA' ])
except KeyError:
print ( 'Not Found' )
|
Time Complexity: The time complexity of the try-except block is O(1).
Space Complexity: The space complexity of the program depends on the size of the dictionary and the message to be printed in the ‘except’ block
Similar Reads
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstra
4 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Dictionary has_key() - Python
The has_key() method in Python was used to check whether a specified key exists in a dictionary. However, this method was removed in Python 3 and the preferred approach to check for a key's existence is by using the in keyword. In Python 2.7, the has_key() method was commonly used, like so: [GFGTABS
3 min read
Flatten given list of dictionaries - Python
We are given a list of dictionaries, and the task is to combine all the key-value pairs into a single dictionary. For example, if we have: d = [{'a': 1}, {'b': 2}, {'c': 3}] then the output will be {'a': 1, 'b': 2, 'c': 3} Using the update() methodIn this method we process each dictionary in the lis
4 min read
Get length of dictionary in Python
Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Letâs explore the various methods. Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in
3 min read
Python Dictionary keys() method
keys() method in Python dictionary returns a view object that displays a list of all the keys in the dictionary. This view is dynamic, meaning it reflects any changes made to the dictionary (like adding or removing keys) after calling the method. Example: [GFGTABS] Python d = {'A': 'Geek
2 min read
Filter List of Dictionaries Based on Key Values in Python
Filtering a list of dictionaries based on specific key values is a common task in Python. This becomes useful when working with large datasets or when we need to select certain entries that meet specific conditions. We can do this using list comprehensions, the filter() function, and simple loops. U
3 min read
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game
3 min read
How to Add Duplicate Keys in Dictionary - Python
In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will explore several techniques to store multiple values for a single dictionary key. Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique.
3 min read
How to Compare List of Dictionaries in Python
Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
3 min read