dict.setdefault()
Gets a key value, inserting default if the key is missing.
value = data.setdefault(key, default)This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Gets a key value, inserting default if the key is missing.
The dict.setdefault() method is used to retrieve the value of a key if it exists in the dictionary; if the key is absent, it inserts the key with a specified default value and returns that value. Internally, this operation is optimized to perform a single lookup in the hash table, making it more efficient than the common 'check then set' pattern (e.g., 'if key not in d: d[key] = []'), which requires two lookups. However, a significant edge case to consider is that the default value expression is evaluated every time the method is called, even if the key already exists. This can lead to performance degradation or side effects if the default value is a complex function call or an expensive object instantiation. In modern Python, while collections.defaultdict is often preferred for readability and avoiding redundant object creation, setdefault() remains a powerful built-in tool for managing dictionary state without additional imports.
Quick reference
Syntax
value = data.setdefault(key, default)
Inputs
Parameters
See it in practice
Examples
Grouping Items into Lists
data = [('fruit', 'apple'), ('veggie', 'carrot'), ('fruit', 'mango')]
registry = {}
for category, item in data:
registry.setdefault(category, []).append(item)
print(registry){'fruit': ['apple', 'mango'], 'veggie': ['carrot']}
Groups items by key. If the key doesn't exist, it initializes an empty list, then appends the item regardless.
Building Nested Dictionaries
config = {}
# Deeply nested assignment in one line
config.setdefault('metadata', {}).setdefault('tags', []).append('python')
print(config){'metadata': {'tags': ['python']}}
Uses setdefault to safely initialize nested dictionaries and lists without checking existence at each level.
Default Value Retrieval
counts = {'a': 1, 'b': 2}
val_a = counts.setdefault('a', 0)
val_c = counts.setdefault('c', 10)
print(f'a: {val_a}, c: {val_c}')
print(counts)a: 1, c: 10 {'a': 1, 'b': 2, 'c': 10}
Returns the existing value for 'a', but inserts and returns the default for the missing key 'c'.
Debug faster
Common Errors
Performance/Side Effect Error
Cause: The default argument is evaluated before the method is called, leading to unnecessary execution if the key already exists.
Fix: Use collections.defaultdict if the default value requires expensive computation or has side effects.
d = {'key': 'exists'}
d.setdefault('key', expensive_function_call()) # function runs even though key existsLogicError
Cause: Confusing setdefault() with get(). Unlike get(), setdefault() modifies the dictionary if the key is missing.
Fix: Use .get() for read-only lookups and .setdefault() only when you intend to update the dictionary with a default.
d = {}
val = d.setdefault('x', [])
# d is now {'x': []}. If you only wanted to check, use d.get('x', [])Runtime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Gets a key value, inserting default if the key is missing.
key: Dictionary key to look up/insert. default: Value inserted and returned if key is missing.
Performance/Side Effect Error: Use collections.defaultdict if the default value requires expensive computation or has side effects. LogicError: Use .get() for read-only lookups and .setdefault() only when you intend to update the dictionary with a default.