defaultdict

say it: “dih-FAWLT-dikt” /dɪˈfɔltˌdɪkt/

A dictionary that fills in a starting value for a new key automatically.

What is a defaultdict?

A defaultdict is a dictionary that fills in a starting value for a key the first time you use it, so you don't have to check whether the key exists.

from collections import defaultdict

sales = defaultdict(int)
for item in ["tea", "coffee", "tea"]:
    sales[item] += 1
print(dict(sales))  # {'tea': 2, 'coffee': 1}

Level: Freelancer · More Python terms at this level

Updated