The get() method returns the value of the specified key in the dictionary.
Example
Syntax of Dictionary get()
The syntax of get() is:
dict.get(key[, value])
get() Parameters
get() method takes maximum of two parameters:
- key - key to be searched in the dictionary
- value (optional) - Value to be returned if the key is not found. The default value is
None.
Return Value from get()
get() method returns:
- the value for the specified key if key is in the dictionary.
Noneif the key is not found and value is not specified.- value if the key is not found and value is specified.
Example 1: How does get() work for dictionaries?
Output
Name: Phill Age: 22 Salary: None Salary: 0.0
Python get() method Vs dict[key] to Access Elements
get() method returns a default value if the key is missing.
However, if the key is not found when you use dict[key], KeyError exception is raised.
Output
Salary: None
Traceback (most recent call last):
File "", line 7, in
print(person['salary'])
KeyError: 'salary'