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.
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
| Parameter | What it is |
|---|---|
keyrequired | The key to look up, and to add if it is missing. |
defaultoptional, 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
settings = {"theme": "dark"}
print(settings.setdefault("theme", "light"))
print(settings.setdefault("font", 14))
print(settings)dark
14
{'theme': 'dark', 'font': 14}"theme" keeps "dark"; "font" was missing, so it was added.
2Group items into lists
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for w in words:
by_letter.setdefault(w[0], []).append(w)
print(by_letter){'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}3get() vs setdefault()
stock = {}
print(stock.get("pens", 0))
print(stock)
print(stock.setdefault("pens", 0))
print(stock)0
{}
0
{'pens': 0}4The same grouping with defaultdict
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)){'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.
prefs = {"lang": "de"}
prefs.setdefault("lang", "en")
print(prefs){'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.