Python dict.setdefault() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
dict method

Definition

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)
CallWhat 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

ParameterDescription
keyThe key to look up or insert. It must be hashable.
defaultOptional. The value stored and returned when key is missing. Defaults to None. Positional only.

Return Value

Return ValueDescription
the stored valueWhen key already exists: its current value, unchanged.
defaultWhen 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))

How It Works

  1. First visit. When Lisbon is seen for the first time, setdefault() stores a new empty list and returns it, so append() adds Ana.
  2. Later visits. For Chen, Lisbon already exists, so the call returns the same list and Chen joins Ana.
  3. City order. Cities appear in the order they were first met: Lisbon, Berlin, Rome.
  4. 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().

python
prefs = {"language": "fr"}

print(prefs.setdefault("language", "en"))
print(prefs.setdefault("units", "metric"))
print(prefs.setdefault("nickname"))
print(prefs.get("theme", "auto"), "theme" in prefs)
print(prefs)

How It Works

  1. Existing key wins. language is already fr, so the default en is ignored and fr is returned.
  2. Missing key stored. units did not exist, so metric is inserted and returned.
  3. Implicit None. Without a second argument the default is None, and that None is stored too.
  4. get() only reads. get() returns auto for the missing theme but never adds it, which is why theme is absent from the final dict.

Example 3 — Build a Two-Level Sales Report

Create an inner dict per region on demand and total quantities per product inside it.

python
sales = [
    ("north", "tea", 4),
    ("south", "tea", 2),
    ("north", "coffee", 5),
    ("north", "tea", 1),
]

report = {}
for region, product, qty in sales:
    region_totals = report.setdefault(region, {})
    region_totals[product] = region_totals.get(product, 0) + qty

print(report)
print(report.get("east", {}), "east" in report)

How It Works

  1. Inner dict on demand. report.setdefault(region, {}) returns the region's dict, creating an empty one the first time.
  2. Same object. region_totals is the dict stored inside report, so writing to it updates the report directly.
  3. Running totals. North tea is counted twice, 4 + 1 = 5, while each other product appears once.
  4. 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.

Next: dict.update()

Merge keys from another dict, a list of pairs, or keyword arguments, in place.

update() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful