The get method
The get method returns the dictionary value by key. If the given key is missing, the default value is used. In the first parameter of the method, we specify the key we need, and in the second optional parameter, the default value.
Syntax
dictionary.get(key, [default value])
Example
Let's find the key 'a' in our dictionary, and specify the default value '!' for it:
dct = {
'a': 1,
'b': 2,
'c': 3
}
dct.get('a', '!')
print(dct)
Result of code execution:
1
Example
Now let's try to get the value of a key that is not in the dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
print(dct.get('e', '!'))
Result of code execution:
!
Example
Let's modify the previous example so that there is no default value for a non-existent key:
dct = {
'a': 1,
'b': 2,
'c': 3
}
print(dct.get('e'))
After executing the code, the method will return us None:
None