Python Dictionary setdefault() Method

Returns the value of the item with the specified key. If the key doesn't exist, the key is inserted into the dictionary with the supplied value, and that value is returned. If the key doesn't exist and no default value is supplied, nothing is returned.

Syntax

Python
dictionary.setdefault(key, value = None)

Parameters

ParameterDescription
key Required. The key of the value to get
default Optional. The default value to set.

Example

Python
fish = {
    'guppy': 2,
    'zebra' : 5,
    'betta': 10
}

# The 'guppy' key exists, so the dictionary in unchanged.
numGuppies = fish.setdefault('guppy', 10)
print(f'I still have {numGuppies} guppies: {fish}')

# But we didn't have any shark!
numShark = fish.setdefault('shark', 1)
print(f'I have {numShark} shark!')

Output

I still have 2 guppies: {'guppy': 2, 'zebra': 5, 'betta': 10}
I have 1 shark!