When would you use Counter or defaultdict over a plain dict?medium

Type
conceptual
Topic
collections
Frequency
common
Tags
Counter, defaultdict, collections, dict
Answer

Counter is for frequency counting — missing keys return 0. defaultdict is for grouping or accumulating — missing keys auto-initialise from a factory.

Explanation

Counter(words) builds a frequency map from an iterable and provides .most_common(n). defaultdict(list) lets you do d[key].append(val) without a KeyError on first access. Use defaultdict(int) for manual counting when you need more control than Counter provides. Both eliminate the dict.get(key, default) boilerplate throughout your code.

Follow-upHow does Counter.most_common work internally and what is its time complexity?