Tutorial Study Image

Python setdefault()

The setdefault() function in python helps to return the value of the key which is in the dictionary. If the key is not in the dictionary, then a new key is inserted with the specified value to the dictionary.


dict.setdefault(key[, default_value]) #where the key is to be searched
 

setdefault() Parameters:

The setdefault() function takes two parameters.If the parameter 'default_value' is not given it will be taken as none.

Parameter Description Required / Optional
key the key to be searched in the dictionary Required
default_value key with a value default_value is inserted into the dictionary if the key is not in the dictionary optional

setdefault() Return Value

The method’s return value depends on the input parameters given.

Input Return Value
if it in a dictionary key-value
if key not in dictionary & no defalt_value None
if key not in dictionary & defalt_value is given default_value

Examples of setdefault() method in Python

Example 1: How setdefault() in python works when key is in the dictionary?


persondet = {'name': 'Jhon', 'age': 35}

age = persondet.setdefault('age')
print('personal details = ',persondet)
print('Age = ',age)
 

Output:


personal details =  {'name': 'Jhon', 'age': 35}
Age =  35

Example 2: How setdefault() works in python when key is not in the dictionary?


persondet = {'name': 'Jhon'}

# key is not in the dictionary
salary = persondet.setdefault('salary')
print('personal details = ',persondet)
print('salary = ',salary)

# key is not in the dictionary
# default_value is provided
age = persondet.setdefault('age', 35)
print('personal details = ',persondet)
print('age = ',age)
 

Output:


personal details =  {'name': 'Jhon', 'salary': None}
salary =  None
personal details =  {'name': 'Jhon', 'age': 35, 'salary': None}
age =  35