Home / Python / Reference / Dictionary methods

Python dictionary setdefault() method

Return a key's value, inserting a default first if the key is missing.

Syntax

dict.setdefault(key, default=None)

A compact way to group things into lists: groups.setdefault(key, []).append(item). collections.defaultdict is an even cleaner alternative.

Parameters

keythe key
defaultinserted if the key is missing

Return value

the value

Example

Code

orders = [("Sita", 30), ("Leo", 12), ("Sita", 18)]
by_customer = {}
for name, amount in orders:
    by_customer.setdefault(name, []).append(amount)
print(by_customer)

Output

{'Sita': [30, 18], 'Leo': [12]}

Related

Learn it step by step in the free lesson Dictionaries & Sets, with exercises that check your answers.