Skip to main content

setdefault()

The setdefault() method in Python dictionary is used to retrieve a value from a dictionary based on a specified key. If the key is present in the dictionary, it returns the corresponding value. If the key is not present, it inserts the key with a specified default value and returns this value. This method helps in avoiding KeyError when attempting to access a key that does not exist in the dictionary.

Parameter Values

Parameter Description
key

The key to be searched in the dictionary.

default

The value to be inserted in the dictionary if the key is not found.

Return Values

The setdefault() method can return any type, as it returns the value of a dictionary key.

How to Use setdefault() in Python

Example 1:

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

my_dict = {'a': 1, 'b': 2}
default_val = my_dict.setdefault('c', 3)
print(default_val) # Output: 3
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}