Skip to content
Tutorials Center
My learning

Topics

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.

Python
groups = {}
groups.setdefault("fruit", []).append("apple")
# {'fruit': ['apple']}

Try it

Python Grouping words by first letter

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.

Python The default is always evaluated

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

Python
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()) runs expensive() every time, even when k exists. For costly defaults use if k not in d: or collections.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 defaultdict for heavy grouping. defaultdict(list) avoids creating a throwaway object on every lookup.
  • get() does not insert. dict.get() returns a default without storing it.