dict.setdefault()

Returns the value of a key, and first stores a default value in the dictionary when the key is missing.

Returns
The value of the key after the call: the existing one, or the one just inserted.
Changes the original
Yes
On this page

Example

#
Python
settings = {"theme": "dark"}

print(settings.setdefault("theme", "light"))
print(settings.setdefault("lang", "en"))
print(settings)
Resultsaved result, you can check it
dark
en
{'theme': 'dark', 'lang': 'en'}

Definition and usage

#

The setdefault(key, default) method works like get() with one difference: when the key is missing, it inserts it into the dictionary with the default value, and only then returns it. When the key exists, it returns its value and changes nothing.

It's most often used for grouping data. Writing groups.setdefault(key, []).append(item) creates an empty list the first time a key appears, and appends to the existing one on every later occurrence. All of that fits on one line.

The default value is created on every call, even when the key exists. For heavy grouping, collections.defaultdict tends to be clearer and faster, since it creates values only when they are actually needed.

Syntax

#
Syntax
dict.setdefault(key, default=None)

Parameters

#
  • key

    a dictionary key

    The key to read or add.
  • default

    optional, default None

    The value inserted when the key is missing.

More examples

#
Grouping in one line
Python
topics = [
    ("HTML", "tags"),
    ("CSS", "flexbox"),
    ("HTML", "forms"),
    ("CSS", "grid"),
]
by_course = {}

for course, topic in topics:
    by_course.setdefault(course, []).append(topic)

print(by_course)
Resultsaved result, you can check it
{'HTML': ['tags', 'forms'], 'CSS': ['flexbox', 'grid']}

Good practices

#
  • For grouping many items, consider defaultdict(list). The code is shorter, and an empty list is not created on every call.
  • If you only want to read a value with a fallback, without storing it in the dictionary, use get().

Related entries

#

Spotted a mistake or missing an example? Write to us.