defaultdict — dictionary that provides default value for missing keys.
1from collections import defaultdict23# Count occurrences4word_count = defaultdict(int)5for word in ["apple", "banana", "apple", "cherry"]:6 word_count[word] += 17print(dict(word_count)) # {'apple': 2, 'banana': 1, 'cherry': 1}89# Group items10groups = defaultdict(list)11for item in [(1, "a"), (1, "b"), (2, "c")]:12 groups[item[0]].append(item[1])13print(dict(groups)) # {1: ['a', 'b'], 2: ['c']}1415# Nested dictionary16nested = defaultdict(lambda: defaultdict(int))17nested["users"]["count"] += 1
vs dict.setdefault():