Python Dictionary setdefault() Method (original) (raw)

Last Updated : 8 Sep, 2025

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

Syntax

dict.setdefault(key, default_value)

**Parameters:

**Return Type:

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:

**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:

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.