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

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Usage and examples of Python dictionary setdefault()

Python dictionary methods

The setdefault() method returns the value of the specified key. If the key does not exist, it inserts a key with the specified value.

The syntax of setdefault() is:

dict.setdefault(key[, default_value])

setdefault() parameters

setdefault() accepts up to two parameters:

  • key -The key to be searched in the dictionary

  • default_value(Optional)- If the key is not in the dictionary, insert the value of the key with the value default_value 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 the key is not in the dictionary and default_value is not specified, it will be None

  • default_value - If the key is not in the dictionary and 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 this 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 this program, the output is:

person =  {'name': 'Phill', 'salary': None}
salary =  None
person =  {'name': 'Phill', 'age': 22, 'salary': None}
age =  22

Python dictionary methods