Python Dictionary setdefault() Method

Returns the value for key if exists, else inserts it

Usage

The setdefault() method returns the value for key if key is in the dictionary.

If not, it inserts key with a value of default and returns default.

Syntax

dictionary.setdefault(key,value)

Python dictionary setdefault() method parameters
ParameterConditionDescription
keyRequiredAny key you want to return value for
defaultOptionalA value to insert if the specified key is not found.
Default value is None.

Basic Example

setdefault() method is generally used to insert a key with a default value.

Example: Insert a key ‘job’ with default value ‘Dev’

D = {'name': 'Bob', 'age': 25}
v = D.setdefault('job', 'Dev')
print(D)    # {'job': 'Dev', 'age': 25, 'name': 'Bob'}
print(v)    # Dev

setdefault() Method Scenarios

The method’s output depends on input parameters. Here are three scenarios for different input parameters.

Key Present

If key is in the dictionary, the method returns the value for key (no matter what you pass in as default)

Example:

D = {'name': 'Bob', 'age': 25}
v = D.setdefault('name')
print(v)    # Bob

Default value is ignored if key is present

D = {'name': 'Bob', 'age': 25}
v = D.setdefault('name', 'Max')
print(v)    # Bob

Key Absent, Default Specified

If key is not in the dictionary, the method inserts key with a value of default and returns default.

Example:

D = {'name': 'Bob', 'age': 25}
v = D.setdefault('job', 'Dev')
print(D)    # {'job': 'Dev', 'age': 25, 'name': 'Bob'}
print(v)    # Dev

Key Absent, Default Not Specified

If key is not in the dictionary and default is not specified, the method inserts key with a value None and returns None.

Example:

D = {'name': 'Bob', 'age': 25}
v = D.setdefault('job')
print(D)    # {'job': None, 'age': 25, 'name': 'Bob'}
print(v)    # None