Python Reference ยท Dictionaries and Sets
Python dict.setdefault() method
Reference for Python dict.setdefault(): get a value or insert a default in one step, grouping patterns, the shared mutable default trap and defaultdict.
The setdefault() method looks up a key. If the key exists, it returns the stored value and changes nothing. If the key is missing, it inserts the key with a default value and returns that default. In both cases you get back the value that is now stored under the key.
Its classic use is grouping or counting: "give me the list for this key, creating an empty one the first time". It does the check and the insert in a single call.
groups = {} groups.setdefault("fruit", []).append("apple") # {'fruit': ['apple']}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
dict.setdefault(key, default=None)
| Name | Description |
|---|---|
key |
The key to look up. It must be hashable. |
default |
Optional. Value to insert when key is missing. Defaults to None. |
Return value: the existing value for key, or default if the key was just inserted.
Raises: TypeError if key is unhashable, for example a list.
Usage notes
- It may mutate the dictionary. A missing key is inserted with the default; an existing key is left alone, even if its value is
None. - The default is always evaluated. Python builds the argument before the call, so
d.setdefault(k, expensive())runsexpensive()every time, even whenkexists. For costly defaults useif k not in d:orcollections.defaultdict. - Mutable defaults are fine here.
setdefault(k, [])creates a new list per call, and only the one for a missing key is kept. Do not reuse one list object across calls by passing a shared variable. - No default means
None.d.setdefault("x")inserts"x": None, which is rarely what you want. - Prefer
defaultdictfor heavy grouping.defaultdict(list)avoids creating a throwaway object on every lookup. get()does not insert.dict.get()returns a default without storing it.
Related
dict.get(),dict.update(),dict.pop()- Lessons: Dictionaries, Dictionary methods