Problem Statement
What is defaultdict? When is it helpful and what pitfalls should you avoid?
Explanation
defaultdict creates missing keys automatically using a factory like list or int, so you can append or add without pre-checks. It reduces boilerplate when grouping items or counting events.
A pitfall is accidental key creation when reading; any access can materialize a key. Convert to a plain dict before serialization if you do not want the default behavior to surprise downstream code.
Code Solution
SolutionRead Only
from collections import defaultdict
groups=defaultdict(list)
for k,v in [('a',1),('a',2)]:
groups[k].append(v)
print(dict(groups))