Python 3 – Dictionary setdefault() Method
Python 3 has a built-in dictionary method called the setdefault()
. The setdefault() method helps in setting the default values of keys that are not present in the dictionary. It takes two parameters – the key to be searched for and the default value, which will be inserted in the dictionary if the key does not exist.
Syntax
The syntax for using the setdefault() method in Python is as follows:
dictionary.setdefault(key, default_value)
Where dictionary
is the dictionary to be searched for the key, key
is the key to be searched for in the dictionary, and default_value
is the value to be inserted in the dictionary if the key is not found.
Example
Let’s see an example of how to use the setdefault() method in Python:
# Initializing dictionary
dictionary = {'one': 1, 'two': 2}
# Using setdefault() method
dictionary.setdefault('three', 3)
print(dictionary)
Output:
{'one': 1, 'two': 2, 'three': 3}
In the example above, we first initialize a dictionary with two keys ‘one’ and ‘two’ and their corresponding values 1 and 2, respectively. Then we use the setdefault() method to search for the key ‘three’. As the key ‘three’ is not present in the dictionary, the method inserts the key ‘three’ with the default value 3 in the dictionary, and the updated dictionary is printed.
Dictionary with Multiple Default Values
The setdefault() method can also be used to set multiple default values if more than one key is not found in the dictionary. For this, we need to pass a dictionary containing the keys and their respective default values as the second parameter to the setdefault() method.
Example
# Initializing dictionary
dictionary = {'one': 1, 'two': 2}
# Using setdefault() method with multiple keys and their default values
dictionary.setdefault('three', 3)
dictionary.setdefault('four', 4)
print(dictionary)
Output:
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
In the example above, we first initialize a dictionary with two keys ‘one’ and ‘two’ and their corresponding values 1 and 2, respectively. Then we use the setdefault() method to search for two keys ‘three’ and ‘four’. As both keys are not present in the dictionary, the method inserts them with their default values 3 and 4, respectively, in the dictionary, and the updated dictionary is printed.
Conclusion
The setdefault() method can be very useful while working with dictionaries in Python. It helps in setting default values for keys that are not present in the dictionary, and thus avoids the need for complex if-else statements to handle such cases.