Dictionary Methods
setdefault()
Return the value of a key; if absent, insert the key with the default value.
dict.setdefault(key, default=None)
dict.setdefault() checks if key is in the dictionary. If present, it returns its existing value.
If the key is not present, it inserts key with the value default and returns default.
Arguments
Parameters
| Name | Description |
|---|---|
| key | The key to look up or insert. |
| default | The value to insert and return if the key is missing. Defaults to None. |
Result
Returns
The existing value for the key, or the newly inserted default value.
Run it
Try it
Run it and change it
groups = {}
groups.setdefault("admin", []).append("Alice")
groups.setdefault("admin", []).append("Bob")
groups.setdefault("guest", []).append("Charlie")
print(groups) Output
Press Run to see what it prints.Worth knowing
- Grouping and accumulation:
setdefault()is commonly used to build lists or sets inside dictionaries without having to initialize empty collections manually.