English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The setdefault() method returns the value of the specified key. If the key does not exist, it inserts a key with the specified value.
The syntax of setdefault() is:
dict.setdefault(key[, default_value])
setdefault() accepts up to two parameters:
key -The key to be searched in the dictionary
default_value(Optional)- If the key is not in the dictionary, insert the value of the key with the value default_value into the dictionary.
If not provided, default_value will be None.
setdefault() returns:
The value of the key (if it is in the dictionary)
None - If the key is not in the dictionary and default_value is not specified, it will be None
default_value - If the key is not in the dictionary and default_value is specified
person = {'name': 'Phill', 'age': 22} age = person.setdefault('age') print('person = ',person) print('Age = ',age)
When running this program, the output is:
person = {'name': 'Phill', 'age': 22} Age = 22
person = {'name': 'Phill'} # key is not in the dictionary salary = person.setdefault('salary') print('person = ',person) print('salary = ',salary) # key is not in the dictionary # provided default_value age = person.setdefault('age', 22) print('person = ',person) print('age = ',age)
When running this program, the output is:
person = {'name': 'Phill', 'salary': None} salary = None person = {'name': 'Phill', 'age': 22, 'salary': None} age = 22