About Python Dictionary:
In this post, we check, how to set default dictionary python value.
Let’s make the thing simple. Take the instance. It will be easy to understand.
Suppose we are maintaining the capitals of BRICS association countries. The mapping of countries involved in BRICS association is mapped with their capitals.
Problem statement:
Write a Python program to find the capital of the BRICS association country. If it is not listed in the Python dictionary, it should return as ‘This Country is not listed in BRICS.’
A dictBRICMap
is dictionarywhich stores the BRICs countries as name and its capital as value.
>>>> dictBRICMap = {'Brazil':'Brasília', 'Russia':'Moscow', 'India':'New Delhi', 'China':'Beijing', 'South Africa':'Cape Town'}
There are two typical ways of getting dictionary value from key:
The easiest way to find the capital of the country enrolled in BRICs is as follows.
>>>> print(dictBRICMap['India']) 'New Delhi'
We can also find it by calling dictionary function dict.get(‘key’) as follows.
>>>> print dictBRICMap.get('India') 'New Delhi'
What if we provide a key which is not present in the dictionary?
It throws an error as follows.
>>>> print dictBRICMap.get('Japan') Traceback (most recent call last): File "", line 1, in KeyError: 'japan'
It does not look good.
What if we display the string as “This country is not listed.” instead of throwing an error?
For this, we need to set the default value for the dictionary.
To tackle this, we can provide the default value for the key using get() method.
If the country does not match with any of the keys in the dictionary, it takes default dictionary python value as follow.
>>>> print(dictBRICMap.get('Japan','This country is not listed in BRICs.')) 'This Country is not listed in BRICs.'
For the end-user perspective, this text looks more genuine.
Many times it is not possible to provide all the dictionary values. Taking default dictionary Python value is good provision to tackle with invalid dictionary keys.
You can also prompt as ‘Key not present in the dictionary’ in general case if the user provides ‘invalid key’.
Quick question: instead of:
print(dictBRICMap.get('Japan','This country is not listed in BRICs.'))
is there a way to reply
'"Japan" is not listed in BRICS'
Thanks.
You can not do it directly. But you can make it happen indirectly.
Super! Thank you. I don’t think I would have thought of doing that. Nice.
You’re welcome!
This is a very nice explanation and helpful for me.
Glad you find it helpful. You’re welcome!