Refactored code to use defaultdict