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.
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. |
Returns
The existing value for the key, or the newly inserted default value.
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)Worth knowing
- Grouping and accumulation:
setdefault()is commonly used to build lists or sets inside dictionaries without having to initialize empty collections manually.