Content · Programming · Python

Python dict.setdefault Method: Usage and Examples

dict.setdefault(key, default=None) returns an existing value, or inserts and returns a default when the key is absent. It mutates the dictionary only for missing keys. See two practical examples, edge cases and common.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A record groups tasks by project without separate existence checks.

What You Need to Understand


dict.setdefault(key, default=None) returns an existing value, or inserts and returns a default when the key is absent. It mutates the dictionary only for missing keys.

When to Use It


A record groups tasks by project without separate existence checks.

Step-by-Step Python Example


tasks = {}
tasks.setdefault("backend", []).append("API")
tasks.setdefault("backend", []).append("Tests")
print(tasks)

How the Example Works


The first call inserts a list. The second returns the existing list, then appends to it.

Example Output


{'backend': ['API', 'Tests']}
{'a': ['apple', 'apricot'], 'p': ['pear']}

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

grouped = {}
for item in ["apple", "apricot", "pear"]:
    grouped.setdefault(item[0], []).append(item)
print(grouped)

Important Behavior and Edge Cases


The default expression is evaluated before setdefault() is called, even if the key exists. For large or expensive defaults, defaultdict or explicit checks may be clearer.

Try It Yourself


Group three fruit names under their initial letters.

Common Beginner Mistakes


  • The default expression is evaluated before setdefault() is called, even if the key exists. For large or expensive defaults, defaultdict or explicit checks may be clearer.
  • Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.

Key Takeaways


  • dict.setdefault(key, default=None) returns an existing value, or inserts and returns a default when the key is absent.
  • The first call inserts a list.
  • The default expression is evaluated before setdefault() is called, even if the key exists.
Share this resourceSend this page to someone who may find it useful.