Grouping by key
Grouping means: for each item compute a key, and collect the items that share it. The values of the dict are lists.
groups = {}
for w in words:
groups.setdefault(w[0], []).append(w)setdefault(key, []) returns the list stored under key, creating an empty one the first time. collections.defaultdict(list) does the same and lets you write groups[key].append(w) directly.
Totals work the same way with numbers: totals[k] = totals.get(k, 0) + amount.
The clever part is the key. Words that are anagrams of each other have the same letters, so "".join(sorted(word)) is a key that is equal for all of them. Two values that should "match" usually share a key you can compute.
In the table, watch each list in groups grow only when its key comes up again.
See it run
groups = {}
for w in ["pear", "plum", "fig", "peach"]:
groups.setdefault(w[0], []).append(w)
print(groups)The key is each word's first letter. Words with the same key go into one list.
Practice grouping by key
Exercise 1
A shelf-labelling machine files every word in words under its first character.
Return a dict whose keys are first characters and whose values are lists of the words with that first character, in the order they appear in words.
Rules:
- Keys are case-sensitive:
"Ax"and"ax"go under different keys. - Words are never empty.
- An empty
wordsgives{}.
Constraints: 0 ≤ len(words) ≤ 10^5.
Example: solution(["pear", "plum", "fig", "peach"]) returns {"p": ["pear", "plum", "peach"], "f": ["fig"]}.
Exercise 2
A café logs each sale as a pair [item, cents] in sales. Refunds are logged as negative amounts.
Return a dict mapping each item name to the total cents over all its sales.
Rules:
- An item that appears only in refunds still gets a key with its (negative) total.
- A total of
0is still included. - Empty
salesgives{}.
Constraints: 0 ≤ len(sales) ≤ 10^5; amounts are integers.
Example: solution([["tea", 300], ["bun", 250], ["tea", 300]]) returns {"tea": 600, "bun": 250}.
Exercise 3
In a word game, two cards match when they contain exactly the same letters, the same number of each, in any order. cards is a list of lowercase words.
Return a list of groups. Each group is a list of the cards that match each other, in the order they appear in cards.
Rules:
- Include only groups with two or more cards.
- Groups are ordered by the position of their first card in
cards. - Two identical words match each other.
- Return
[]when no cards match.
Constraints: 0 ≤ len(cards) ≤ 10^4; each card has 1 to 10 letters.
Example: solution(["tab", "bat", "cup", "abt"]) returns [["tab", "bat", "abt"]].
Exercise 4
Students sign up for clubs. signups is a list of [student, club] pairs; a student may sign up for the same club more than once, which still counts as one member.
Return a list of the club names that have the most distinct members, sorted alphabetically.
Rules:
- If several clubs tie for the most members, return all of them.
- Empty
signupsgives[].
Constraints: 0 ≤ len(signups) ≤ 10^5.
Example: solution([["ann","chess"], ["bo","chess"], ["ann","art"], ["cy","art"], ["ann","chess"]]) returns ["art", "chess"]: each has two distinct students (the repeat of ann in chess is ignored).
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.