Python Dictionary setdefault() Method

The dict.setdefault() method returns the value of the specified key in the dictionary. If the key is not found, then it adds the key with the specified defaultvalue. If the defaultvalue parameter is not specified, then it set None.

Syntax:

dict.setdefault(key, defaultValue)

Parameters:

  1. key: Required. The key to be searched for.
  2. defaultValue: Optional. If the key is not found, it is inserted in the dictionary with this defaultValue. By default, it is None.

Return Value:

Returns the value of the key if the key is present.
Returns the defaultValue if the key is not present or None if defaultvalue is not specified.

The following example demonstrates the dict.setdefault().

Example: setdefault()
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.setdefault('I')

print("The return value is: ", value)
Output
The return value is:  1

If the specified key is not found in the dictionary, then the key is inserted into the dictionary with the specified value. If the value is not specified, it is None.

Example: setdefault()
romanNums = {'I':1, 'II':2, 'III':3}
value = romanNums.setdefault('IV')

print("The return value is: ",value)
print("Updated dictionary: ",romanNums)
Output
The return value is:  None
Updated dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': None}

In the above example, the specified key is not present in the dictionary, so when the method is called, the key is added to the dictionary, with a value of None.

If the key passed as the argument is not present in the dictionary, the key is inserted into the dictionary with the specified value.

Example: Add Key-Value
romanNums = {'I':1, 'II':2, 'III':3 }
value = romanNums.setdefault('VI', 4)

print("The return value is: ",value)
print("Updated dictionary: ",romanNums)
Output
The return value is: 4
Updated dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4 }