![]() |
VOOZH | about |
The setdefault() method in Python is used with dictionaries to:
It’s a handy method for setting default values while avoiding overwriting existing ones.
For example: suppose we're tracking student attendance in a dictionary. Each student's name is a key, and the value is a list of dates they were present. When a student shows up, we want to add the date to their list. If their name isn’t in the dictionary yet, we need to create an entry first. Instead of checking every time if the name exists, we can use setdefault() to do both in one step- check and set a default list if needed
dict.setdefault(key, default_value)
Parameters:
Return Type:
This example shows that setdefault() returns the value of the existing key and doesn’t modify the dictionary.
setdefault() returned: 98
After using setdefault(): {'a': 97, 'b': 98}
Explanation:
Here, a new key-value pair is added since the key doesn’t exist.
Before setdefault(): {'A': 'Geeks', 'B': 'For'}
Returned value: Geeks
After setdefault(): {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
Explanation:
This demonstrates using setdefault() to add a special key with a default value.
Explanation: The space character ' ' is not present, so it’s added with value 32.