How setdefault() works in Python

The inbuilt setdefault() method in Python is used to return the value of a key in a dictionary.

Syntax

dict.setdefault(key, value)

Parameters and return value

The setdefault() method requires one parameter to be passed, which is the key of the corresponding value you want to return.

In addition, an optional value parameter can be passed, which becomes the value of the key. This works if the provided key does not exist in the dictionary.

  • If key exists in the dictionary, its corresponding value is returned.
  • If key doesn’t exist in the dictionary, the provided value is returned.
  • If key doesn’t exist in the dictionary, and value isn’t provided, the method returns None.

Example #1

#When the provided key exists in the dictionary
postcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606, 'civic':2601})
civic_code = postcodes.setdefault('civic')
print("The postcode of Civic is:", civic_code)

Example #2

#When the provided key doesn't exist in the dictionary and
#value is provided
postcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606})
civic_code = postcodes.setdefault('civic', 2601)
print("The postcode of Civic is:", civic_code)

Example #3

#When the provided key doesn't exist in the dictionary and
#value isn't provided
postcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606})
civic_code = postcodes.setdefault('civic')
print("The postcode of Civic is:", civic_code)