English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode setdefault() retourne la valeur de la clé spécifiée. Si la clé n'existe pas, une clé avec la valeur spécifiée est insérée.
La syntaxe de setdefault() est :
dict.setdefault(key[, default_value])
setdefault() can accept up to two parameters:
key -The key to search for in the dictionary
default_value(Optional)- If the key is not in the dictionary, it will insert the value of the key with the value default_value into the dictionary.
If no default_value is provided, it 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 no default_value is specified, it will be None
default_value - If the key is not in the dictionary and a default_value is specified
person = {'name': 'Phill', 'age': 22} age = person.setdefault('age') print('person = ',person) print('Age = ',age)
When running the 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 the program, the output is:
person = {'name': 'Phill', 'salary': None} salary = None person = {'name': 'Phill', 'age': 22, 'salary': None} age = 22