← Data Structures
12 / 25
Lesson 12 — Hash maps: grouping
Hash maps for grouping
A dict can map a key to a list, which lets you group items. Here we group words that are anagrams of each other: the key is the word's letters sorted ("listen" → "eilnst"), so all anagrams share one key. d.setdefault(key, []) returns the list for key, creating an empty one first if needed.
groups = {}
groups.setdefault("eilnst", []).append("listen")
Why it matters: "group orders by customer", "group log lines by error type" — group-by with a dict is one of the most useful tricks you will learn.
Want it another way?
Task
Compute the key (sorted letters joined into a string) and append the word to its group.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.