Algorithmshashmap grouping

Grouping Values with Hash Maps

TT
Testlaa Team
May 14, 20261 min read

Grouping with dict of lists (defaultdict(list)) collects all values sharing a key—classic for anagram buckets, vertical order traversal, or user→events.

Why this shows up in the real world

CRM groups tickets by account; ETL partitions rows by shard key.

Core idea (explained for students)

groups[key].append(item) then optionally sort each group. For immutable result convert inner lists to tuples if keys need hashing elsewhere.

Try this in Python

from collections import defaultdict


def group_by_mod(nums: list[int], m: int) -> dict[int, list[int]]:
    g: dict[int, list[int]] = defaultdict(list)
    for x in nums:
        g[x % m].append(x)
    return dict(g)


print(group_by_mod([1, 2, 3, 4, 5], 3))

Common mistakes

  • Accidentally sharing same list object across keys—never d.setdefault(k, []).append bug if you reused a literal incorrectly (rare).

Key takeaways

  • itertools.groupby requires sorted input—different from hash grouping.
  • For large groups, consider generators instead of materializing all lists.

Tags:

Hashing & frequencyPythonStudents