English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
If the key is in the dictionary, the get() method returns the value of the specified key.
The syntax of get():
dict.get(key[, value])
The get() method can use up to two parameters:
key -The key to be searched in the dictionary
value(Optional)-If the key is not found, then return value. The default value is None.
get() method returns:
If the key is in the dictionary, the value of the key is specified.
None - If the key is not found and no value is specified.
value - If the key is not found and a value is specified.
person = {'name': 'Phill', 'age': 22{} print('Name: ', person.get('name')) print('Age: ', person.get('age')) # No value provided print('Salary: ', person.get('salary')) # Provide value print('Salary: ', person.get('salary', 0.0))
When running this program, the output is:
Name: Phill Age: 22 Salary: None Salary: 0.0
If the key lacks the get() method, the default value is returned.
However, if the key is not found when using dict[key], a KeyError exception will be raised.
print('Salary: ', person.get('salary')) print(person['salary'])
When running this program, the output is:
Traceback (most recent call last): File '...', line 1, in <module> print('Salary: ', person.get('salary')) NameError: name 'person' is not defined