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
Example
#settings = {"theme": "dark"}
print(settings.setdefault("theme", "light"))
print(settings.setdefault("lang", "en"))
print(settings)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
#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
#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)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.