Dict Methods
dict.setdefault()
Returns the stored value if the key is present. If absent, stores the supplied default object and returns it. This supports grouping values into per-key containers. The default argument is evaluated before the call even on a hit, so this is not a lazy factory. Existing None or other falsy values are not replaced. Do not share one mutable default across keys unless intentional.
Formal Syntax & Structure
python syntaxpython
mapping.setdefault(key, default=None, /)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | Hashable | Key to locate using hashing and equality. |
| default | object | Object inserted on a miss; defaults to None. |
Return Value
object
Existing value or newly inserted default object.
Working Example
Example Snippetpython
groups = {}for category, name in [("fruit", "pear"), ("tool", "saw"), ("fruit", "plum")]: groups.setdefault(category, []).append(name)print(groups)print(groups.setdefault("fruit", ["ignored"]))