Handling Missing Keys in Python Dictionaries

# Python code to showcase the dictionary and
# missing value error

# initializing the dictionary

d = { `a` : 1 , ` b` : 2 }

# trying to display the value of the missing key

print ( "The value associated with` c` is: " )

print (d [ ` c` ])


 Traceback (most recent call last): File "46a9aac96614587f5b794e451a8f4f5f.py", line 9, in print (d [`c`]) KeyError:` c` 

In the above example, no key named “c” in the dictionary did not give a runtime error. To avoid such conditions and to alert the user that a specific key is missing or send a default message to that location, there are several ways to handle missing keys.

Method 1: Using get ()

The get (key, def_val) method is useful when we need to validate a key. If the key is present, the value associated with the key is printed, otherwise the def_value passed in arguments is returned.

Method 2: Using setdefault ()

setdefault (key, def_value) works like get (), but the difference is that every time key is missing, a new key is created with a def_value associated with the key passed to arguments.

To implement the above functions, click

# Python code to demonstrate defaultdict

# import & quot; collections & quot; for defaultdict

import collections

# default declaration
# sets the default value "Key not found" for missing keys

defd = collections. defaultdict ( lambda : `Key Not found` )

# initializing values ​​

defd [ `a` ] = 1

# initializing values ​​

defd [ `b` ] = 2

# print value

print ( "The value associated with` a` is: " , end = "")

print (defd [ `a` ])

# print value associated with & # 39; c & # 39;

print ( "The value associated with` c` is: " , end = " ")

print ( defd [ `c` ])


 The value associated with `a` is: 1 The value associated with` c` is: Key Not found 

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.