Open In App

Handling missing keys in Python dictionaries

Last Updated : 22 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python code to demonstrate Dictionary and
# missing value error
d = { 'a' : 1 , 'b' : 2 }
 
# trying to output value of absent key
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")


Output

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'}
 
# search dictionary for country code of India
print(country_code.get('India', 'Not Found'))
 
# search dictionary for country code of Japan
print(country_code.get('Japan', 'Not Found'))


Output

0091
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'}
 
# Set a default value for Japan
country_code.setdefault('Japan', 'Not Present')
 
# search dictionary for country code of India
print(country_code['India'])
 
# search dictionary for country code of Japan
print(country_code['Japan'])


Output

0091
Not Present

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




# Python code to demonstrate defaultdict
import collections
 
# declaring defaultdict
# sets default value 'Key Not found' to absent keys
defd = collections.defaultdict(lambda : 'Key Not found')
 
# initializing values
defd['a'] = 1
 
# initializing values
defd['b'] = 2
 
# printing value
print ("The value associated with 'a' is : ",end="")
print (defd['a'])
 
# printing value associated with 'c'
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')


Output

0091
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 - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Python | Difference in keys of two dictionaries
In this article, we will be given two dictionaries dic1 and dic2 which may contain the same keys and we have to find the difference of keys in the given dictionaries using Python. Example Input: dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}, dict2= {'key1':'Geeks', 'key2':'Portal'} Output: key3 Explanation: key1 and key2 is already present
5 min read
Python | Intersect two dictionaries through keys
Given two dictionaries, the task is to find the intersection of these two dictionaries through keys. Let's see different ways to do this task. Method #1: Using dict comprehension C/C++ Code # Python code to demonstrate # intersection of two dictionaries # using dict comprehension # initialising dictionary ini_dict1 = {'nikhil': 1, 'vashu' : 5, 'man
4 min read
Python - Compare Dictionaries on certain Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to compare dictionaries for equality on bases in selected keys. This kind of problem is common and has application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force way in which this task
5 min read
Python - Concatenate values with same keys in a list of dictionaries
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let's discuss the certain ways in which this task can be
7 min read
Combine keys in a list of dictionaries in Python
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let's discuss a way in which this task can be performed. Input : test_list = [{'a': 6}, {'b': 2}, {'a': 9}, {'b': 7}] Output : [{'b': 2, '
2 min read
Python - Extract Maximum Keys' value dictionaries
Given a dictionary, extract all the dictionary which contains a any key which has maximum values among other keys in dictionary list. Input : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "Best" : 14}] Output : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2
6 min read
Python program to extract N largest dictionaries keys
Given a dictionary, extract the largest N dictionaries keys in descending order. Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 3 Output : [10, 8, 6] Explanation : Max. N keys extracted in descending order.Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 2 Output : [10, 8] Explanation : Max. N keys extracted in descending order. Method #1 :
5 min read