setdefault() is a lookup that can also insert. If the key exists, it returns the stored value and changes nothing. If the key is missing, it stores the default under that key and returns it.
Because it returns the value that is now in the dict, you can chain a call onto it. The best-known use is grouping: groups.setdefault(key, []).append(item) creates each list on first use and appends to it every time.
dict.setdefault() is an instance method of the built-in dict type: call it on a dictionary with dot notation, such as by_city.setdefault(...). No import is needed.
Syntax
Pass the key, and optionally the default to store when it is missing.
python
value = d.setdefault(key)
value = d.setdefault(key, default)
d.setdefault(group, []).append(item)
Call
What it does
{"a": 1}.setdefault("a", 5)
Returns 1; the existing value is kept.
{"a": 1}.setdefault("b", 5)
Returns 5; the dict becomes {'a': 1, 'b': 5}.
groups.setdefault("x", []).append(1)
Creates the list for "x" on first use, then appends to it.
Compare with get(): both return the existing value, but only setdefault() stores the default when the key is missing.
Method signatures
python
dict.setdefault(key, default=None, /)
# returns: d[key], after storing default if key was missing
Parameters
Parameter
Description
key
The key to look up or insert. It must be hashable.
default
Optional. The value stored and returned when key is missing. Defaults to None. Positional only.
Return Value
Return Value
Description
the stored value
When key already exists: its current value, unchanged.
default
When key was missing: the default, which is now stored in the dict.
Python Examples
Example 1 — Group Contacts by City
Turn a flat list of (name, city) pairs into a dict of lists in one pass.
python
people = [
("Ana", "Lisbon"),
("Ben", "Berlin"),
("Chen", "Lisbon"),
("Dia", "Rome"),
("Eli", "Berlin"),
]
by_city = {}
for name, city in people:
by_city.setdefault(city, []).append(name)
print(by_city)
for city, names in by_city.items():
print(city, len(names), ", ".join(names))
Output
{'Lisbon': ['Ana', 'Chen'], 'Berlin': ['Ben', 'Eli'], 'Rome': ['Dia']}
Lisbon 2 Ana, Chen
Berlin 2 Ben, Eli
Rome 1 Dia
How It Works
First visit. When Lisbon is seen for the first time, setdefault() stores a new empty list and returns it, so append() adds Ana.
Later visits. For Chen, Lisbon already exists, so the call returns the same list and Chen joins Ana.
City order. Cities appear in the order they were first met: Lisbon, Berlin, Rome.
Read the groups.items() unpacks each city with its list, and ", ".join() prints the names on one line.
Example 2 — Fill In Missing Preferences
Watch setdefault() keep an existing value, insert a new one, insert None, and compare it with get().
Inner dict on demand.report.setdefault(region, {}) returns the region's dict, creating an empty one the first time.
Same object.region_totals is the dict stored inside report, so writing to it updates the report directly.
Running totals. North tea is counted twice, 4 + 1 = 5, while each other product appears once.
Peek without creating. Reading east with get() returns a temporary empty dict and leaves the report unchanged, unlike setdefault().
Frequently Asked Questions
If the key exists, it returns the value. If not, it stores the default under the key and returns that default. The default is None unless you pass one.
Both return the existing value. When the key is missing, get() just returns the default, while setdefault() also stores it in the dict.
Use groups.setdefault(key, []).append(item) inside a loop. The first call for each key creates the list and later calls reuse it.
No. If the key is already present, its value is returned unchanged and the default you pass is ignored.
Use defaultdict when every missing key needs the same kind of default, such as an empty list. setdefault() is handy on a regular dict or when the default differs per call.