Python Dictionary setdefault() Method (original) (raw)
Last Updated : 8 Sep, 2025
The setdefault() method in Python is used with dictionaries to:
- Return the value of a specified key if it exists.
- If the key does not exist, it adds the key with a default value and returns that default.
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
Syntax
dict.setdefault(key, default_value)
**Parameters:
- **key - Key to be searched in the dictionary.
- **default_value (optional) - Key with a value **default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the **default_value will be **None.
**Return Type:
- Value of the key if it is in the dictionary.
- None if key is not in the dictionary and default_value is not specified.
- default_value if key is not in the dictionary and default_value is specified.
Examples of setdefault() Method:
**Example 1: When Key Already Exists
This example shows that **setdefault() returns the value of the existing key and doesn’t modify the dictionary.
Python `
d = {'a': 97, 'b': 98} print("setdefault() returned:", d.setdefault('b', 99)) print("After using setdefault():", d)
`
Output
setdefault() returned: 98 After using setdefault(): {'a': 97, 'b': 98}
**Explanation:
- ****'b'** already **exists with value **98.
- **setdefault('b', 99) returns **98 without changing the dictionary.
**Example 2: When Key Does Not Exist
Here, a new key-value pair is added since the key doesn’t exist.
Python `
d = {'A': 'Geeks', 'B': 'For'}
print("Before setdefault():", d)
val = d.setdefault('C', 'Geeks')
print("Returned value:", val) print("After setdefault():", d)
`
Output
Before setdefault(): {'A': 'Geeks', 'B': 'For'} Returned value: Geeks After setdefault(): {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
**Explanation:
- ****'C'** wasn’t in the dictionary, so it gets added with the value "**Geeks".
- **setdefault() returns the new value assigned to '**C'.
Example 3: Using setdefault() to Insert Special Characters or Defaults
This demonstrates using **setdefault() to add a special key with a default value.
Python `
d = {'a': 97, 'b': 98, 'c': 99, 'd': 100}
d.setdefault(' ', 32)
print(d)
`
**Explanation: The space character ' ' is not present, so it’s added with value **32.