Remi_TRish
Remi_TRish

Reputation: 213

not showing error to indicating missing keys in dictionary using python

I am trying the below code to find missing keys in dictionary. It should function like if the user tries to access a missing key, an error need to popped indicating missing keys.

# missing value error
# initializing Dictionary
d = { 'a' : 1 , 'b' : 2 }
 
# trying to output value of absent key
print ("The value associated with 'c' is : ")
print (d['c'])

getting below error

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

Upvotes: 1

Views: 49

Answers (1)

Rahila T - Intel
Rahila T - Intel

Reputation: 862

In the above 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, we can use 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.

eg :

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 Present

Upvotes: 3

Related Questions