Grouping with itertools.groupby in Python

Level 5409 keystrokes

This groups consecutive items using itertools.groupby. The data is sorted by the grouping key first so that equal keys are adjacent.

Python code

# Import groupby from itertools for grouping
# groupby groups consecutive elements with same key
1from itertools import groupby
# Import itemgetter for extracting dict values
# Creates callable that gets item by key
2from operator import itemgetter
3
# data is a list of employee dictionaries
# Each dict has name and dept keys
4data = [
5 {"name": "Alice", "dept": "Engineering"},
6 {"name": "Bob", "dept": "Engineering"},
7 {"name": "Carol", "dept": "Sales"},
8 {"name": "David", "dept": "Sales"},
9]
10
# Sort data by department before groupby
# groupby only groups consecutive items
11sorted_data = sorted(data, key=itemgetter("dept"))
# Iterate over groups created by groupby
# dept is the group key, group is iterator of items
12for dept, group in groupby(sorted_data, key=itemgetter("dept")):
# Extract names from group into list
# group is an iterator, consumed once
13 members = [p["name"] for p in group]
# Print department and its members
14 print(f"{dept}: {members}")

Output

Engineering: ['Alice', 'Bob']
Sales: ['Carol', 'David']
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 40
  • ,× 11
  • :× 10
  • {× 6
  • }× 6
  • (× 5
  • )× 5
  • =× 5
  • [× 3
  • ]× 3

More Python examples at level 5

← Python typing practice