In this lesson, you learned the pythonic way to retrieve data from dictionaries. Dictionary objects have a get()
method that allows you to retrieve data without raising errors when the requested data does not exist. get()
takes an optional default value as an argument.
The code sample below shows the correct way to retrieve data from a dictionary using get()
:
1dictionary = {'Mahdi': 5, 'Lizbon': 6}
2
3# dict.get() takes a second value as a default
4his_apples = dictionary.get('Mahdi', 0)
5her_apples = dictionary.get('Jennifer', 0)
Instead of raising a KeyError
, line 5 will simply return 0. This approach is much better than trying to access dictionary keys and then catching any errors that may arise.
DanielHao5 on March 13, 2019
Good Tips. Another question is - how to set the dictionary first? Meaning to initiaize the dictionary - more Pathonic way? Thanks.