Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

dict.setdefault

Looks up a key and inserts the given default only when the key is missing.

Version: Python 3.14; repository image, production runtime not attested

Syntax

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

Looks up a key and inserts the given default only when the key is missing.

An existing value wins even when a different default is provided.

An existing binding is returned unchanged, even if its value is None or another falsy value. The example preserves three under a and inserts nine only for the previously absent b. Omitting the default would insert None for a missing key.

d = {"a": None}
assert d.setdefault("a", 9) is None and d.setdefault("b") is None and "b" in d

Examples

m = {"a": 3}
print(m.setdefault("a", 9))
print(m.setdefault("b", 9))
print(m)

Result

3
9
{'a': 3, 'b': 9}

An existing binding is returned unchanged, even if its value is None or another falsy value. The example preserves three under a and inserts nine only for the previously absent b. Omitting the default would insert None for a missing key.

Sources