English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
El método setdefault() devuelve el valor de la clave especificada. Si la clave no existe, se inserta una clave con el valor especificado.
La sintaxis de setdefault() es:
dict.setdefault(key[, default_value])
setdefault() can accept up to two parameters:
key -The key to search in the dictionary
default_value(Optional)- If key is not in the dictionary, it will insert the value of default_value with the key 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 key is not in the dictionary and default_value is not specified, it will be None
default_value - If 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 not in dictionary salary = person.setdefault('salary') print('person = ',person) print('salary = ',salary) # key not in 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