Python’s dictionary object type provides a function get() to return the value of the key in a dictionary. The difference between get() method and using bracket to index the key is that get() will return NULL in result when the key is not present, while the latter raises an error for nonexistent key. Following code example shows using get() with default value for the key in a dictionary.
#create a dictionary
d = {'Wilson': 32, 'Dudu': 20, 'Maomao': 22}
#return value of 'Wilson'
print(d.get('Wilson'))
#output, since value is present, it works
32
#alternative way using brackets
print(d['Wilson'])
#output, since value is present, it works
32
#if we use brackets for a nonexistent key, error comes
print(d['Mia'])
#output
KeyError: 'Mia'
#Python get() Method with default parameter.
print(d.get('Mia', "Not found"))
#output
Not found
get() methods applies for nested dictionary too.
## using nested get()
test_dict = {'Wilson': {'Age': 32, 'Gender': 'male'}, 'Dudu': {'Age': 20, 'Gender': 'male'}, 'Maomao': {'Age': 22, 'Gender': 'male'}}
res = test_dict.get('Wilson', {}).get('Age')
res
0 Comments