The get() method is a very useful method for retrieving values from dictionaries. While methods like keys(), values(), and items() are also useful for retrieving values from dictionaries, the get() method is unique in that it let’s you specify a default value that will be returned if the key you’ve tried to retrieve from the dictionary does not exist.
For example, say I have the below dictionary:
inventory = {"shoes": 23, "phones": 4, "blankets": 1}
print('There are currently ' + str(inventory.get('shoes', 0)) + ' shoes available' )
When I run this short script, I get the below result:
'There are currently 23 shoes available'
On the other hand, even if I specify a key that doesn’t exist in the dictionary, the result gives the default alternative value I specify. For example:
inventory = {"shoes": 23, "phones": 4, "blankets": 1}
print('There are currently ' + str(inventory.get('cars', 0)) + ' cars available' )
Now if I run this script, I get the below result:
There are currently 0 cars available
If I didn’t use the get() method to retrieve the value of a key that didn’t exist, the script would return an error. For example:
inventory = {"shoes": 23, "phones": 4, "blankets": 1}
print('There are currently ' + str(inventory['cars']) + ' cars available' )
Running this script returns the following error:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Input In [11], in <cell line: 2>()
1 inventory = {"shoes": 23, "phones": 4, "blankets": 1}
----> 2 print('There are currently ' + str(inventory['cars']) + ' cars available' )
KeyError: 'cars'