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

Tutoriales básicos de Python

Control de flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de archivos de Python

Objetos y clases de Python

Fecha y hora de Python

Conocimientos avanzados de Python

Manual de referencia de Python

Uso y ejemplo de setdefault() en el diccionario de Python

Python dictionary methods

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

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

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

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

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

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

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

Python dictionary methods