Using defaultdict in place of if statement
Refactoring the code and adding comments