Simplify code with defaultdict