Dictionary method

dict.setdefault()

Returns the value of a key. If the key is missing, it first adds it with the default value, then returns that default.

IntermediateEvery example below runs in your browser. Change the code and press Run.

dict.setdefault(key, default=None, /)

setdefault() is dict.get() with a side effect: when the key is missing, it stores the default under that key before returning it. When the key exists, it returns the current value and changes nothing.

Its favourite job is grouping: groups.setdefault(key, []).append(item) makes sure there is a list for the key and adds to it, in one line.

Watch out: the default is built every time you call setdefault(), even when the key already exists and the default is thrown away. For an expensive default, or for lots of grouping, collections.defaultdict is cleaner.

Parameters

ParameterWhat it is
key
required
The key to look up, and to add if it is missing.
default
optional, default None
The value stored and returned when the key is missing. Give it by position, d.setdefault(key, []): default=[] raises TypeError.

Return value

The value for key: the existing one, or default if it was just added.

Examples

1Existing key vs missing key

Pythoneditable
settings = {"theme": "dark"}
print(settings.setdefault("theme", "light"))
print(settings.setdefault("font", 14))
print(settings)
Output
dark
14
{'theme': 'dark', 'font': 14}

"theme" keeps "dark"; "font" was missing, so it was added.

2Group items into lists

Pythoneditable
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for w in words:
    by_letter.setdefault(w[0], []).append(w)
print(by_letter)
Output
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

3get() vs setdefault()

Pythoneditable
stock = {}
print(stock.get("pens", 0))
print(stock)
print(stock.setdefault("pens", 0))
print(stock)
Output
0
{}
0
{'pens': 0}

4The same grouping with defaultdict

Pythoneditable
from collections import defaultdict
orders = [("Lena", 12.5), ("Omar", 8.0), ("Lena", 4.0)]
by_customer = defaultdict(list)
for name, amount in orders:
    by_customer[name].append(amount)
print(dict(by_customer))
Output
{'Lena': [12.5, 4.0], 'Omar': [8.0]}

Common mistakes

Expecting setdefault() to overwrite

If the key exists, its value is kept. To set a value no matter what, assign it: d[key] = value.

Pythoneditable
prefs = {"lang": "de"}
prefs.setdefault("lang", "en")
print(prefs)
Output
{'lang': 'de'}

Forgetting that the default is created every time

d.setdefault(k, expensive()) runs expensive() even when k is already there. Check with in first, or use defaultdict.

Questions people ask

What is the difference between get() and setdefault()?

Both return a default for a missing key. Only setdefault() also stores that default in the dictionary.

setdefault or defaultdict?

setdefault() works on any normal dictionary and is fine for a few calls. defaultdict is shorter and faster when every missing key should start with the same default, such as an empty list or 0.

How do I add a key only if it does not exist?

d.setdefault(key, value) does exactly that.

Spotted a mistake on this page? Tell us