English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode setdefault() de dictionnaire Python et exemples

Python dictionary methods

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() parameters

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

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

Example1:How does setdefault() work when the key is in the dictionary?

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

Example2:How does setdefault() work when the key is not in the dictionary?

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

Python dictionary methods