Python Dictionary setdefault() Method
dict.setdefault(key, default=None) returns the value for key if it exists; otherwise it stores default under key and returns it. It is a read that creates the entry on first use.setdefault() solves a very common pattern: "if this key is not in the dictionary yet, create it, then use it". It turns three lines (check, create, read) into one call. It is most often used to group items into lists or to initialise counters, and it is one of the key dictionary methods.
Compare it with dict.get(), which also supplies a fallback but never stores it.
| Syntax | my_dict.setdefault(key) or my_dict.setdefault(key, default) |
|---|---|
| Parameters | key: the key to look up; default: value to insert if the key is missing (defaults to None) |
| Returns | The existing value, or the default that was just stored |
| Changes the dictionary? | Only when the key is missing |
| Time complexity | O(1) on average |
How setdefault() reads and creates in one call
If the key exists, setdefault() behaves exactly like get() and leaves the stored value untouched, even if you pass a different default. If the key does not exist, it inserts the pair and returns the new value.
d = {"a": 1}
print(d.setdefault("a", 99))
print(d.setdefault("b", 2))
print(d)The first call ignores 99 because "a" is already there.
Grouping items into lists with setdefault()
Since the returned value is the object stored in the dictionary, you can call a method on it straight away. groups.setdefault(key, []).append(item) creates the list the first time a key appears and appends to it every time. This is the classic way to group data without an if statement. The standard library's collections.defaultdict(list) does the same job with slightly less typing once you know it.
There is one catch: the default argument is created on every call, even if the key exists. With [] that is cheap, but for a costly expression it wastes time.
setdefault() vs get() vs square brackets
| Call | Key missing | Stores the default? |
|---|---|---|
d[k] | Raises KeyError | No |
d.get(k, x) | Returns x | No |
d.setdefault(k, x) | Returns x | Yes |
Examples you can run
Press Run, then edit the code and run it again.
Group students by grade
A new list is created for each grade the first time it is seen.
students = [("Asha", "A"), ("Ravi", "B"), ("Meera", "A"), ("John", "B")]
by_grade = {}
for name, grade in students:
by_grade.setdefault(grade, []).append(name)
print(by_grade)Expected output{'A': ['Asha', 'Meera'], 'B': ['Ravi', 'John']}
Existing value is never overwritten
The returned value is the stored one, not the default you passed.
stock = {"apples": 4}
print(stock.setdefault("apples", 100))
print(stock.setdefault("pears", 0))
print(stock)Expected output4
0
{'apples': 4, 'pears': 0}
Count letters with setdefault()
The returned value is a number, so we store the incremented number back.
counts = {}
for ch in "banana":
counts[ch] = counts.setdefault(ch, 0) + 1
print(counts)Expected output{'b': 1, 'a': 3, 'n': 2}
Common mistakes
Expecting setdefault() to replace a value
✗ Wrong
d = {"mode": "light"}
d.setdefault("mode", "dark")
print(d)✓ Right
d = {"mode": "light"}
d["mode"] = "dark"
print(d)setdefault() only sets a missing key. To overwrite, assign with d["mode"] = "dark" or use update().
Using setdefault() where get() is enough
✗ Wrong
prices = {"pen": 3}
print(prices.setdefault("book", 0))
print(prices)✓ Right
prices = {"pen": 3}
print(prices.get("book", 0))
print(prices)If you only need a fallback value, use prices.get("book", 0) so the dictionary stays unchanged.
Python Dictionary setdefault() Method: questions people ask
What does setdefault() do in Python?
It returns the value of a key if it exists, and otherwise inserts the key with the default value and returns that default.
What is the difference between get() and setdefault()?
get() returns a fallback without storing it, while setdefault() stores the fallback in the dictionary when the key is missing.
Should I use setdefault() or defaultdict?
Both work for grouping and counting. setdefault() needs no import and suits one-off cases, while collections.defaultdict is shorter when you do it repeatedly.
Keep learning
Step-by-step lessons:
Python DictionariesPython Dictionary MethodsPython KeyError: What It Means and How to Fix It
Related:
Python Dictionary get() MethodPython Dictionary update() MethodPython Dictionary pop() MethodHow to Loop Through a Dictionary in Python
More in dictionary methods:
Python Dictionary get() MethodPython Dictionary items() MethodPython Dictionary keys() MethodPython Dictionary values() MethodPython Dictionary update() MethodPython Dictionary pop() MethodPython Dictionary popitem() MethodPython Dictionary clear() Method See all →