Code RoomDefensive setdefault on defaultdict
HardPrep Room Coding #2117

Defensive setdefault on defaultdict

Code reviewCode quality & reviewSenior–Staff~20 min

Review this Python grouping that also tracks counts.

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.

0:00 of about 20 min
Mark a line and say what kind of problem it is.0 findings
1from collections import defaultdict
2 
3def group(records):
4 groups = defaultdict(list)
5 counts = defaultdict(int)
6 for r in records:
7 groups[r.key].append(r)
8 # “defensive”: make sure the key exists in counts before incrementing
9 counts.setdefault(r.key, 0)
10 counts[r.key] = counts[r.key] + 1
11 return groups, counts
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.