Lesson 5 of 10

Grouping with defaultdict

Goal

Group into buckets without a KeyError

01

Explanation

Grouping turns one long list into buckets, like students by city or orders by customer. A plain dict trips over the first item of every bucket, because groups[city].append(name) raises KeyError as long as that city's list hasn't been created yet.

defaultdict(list) from collections solves this: ask it for a key that doesn't exist and it creates an empty list for it and hands it to you, so grouping becomes a single line inside the loop. Note that what you pass in is a function that makes the starting value, not the value itself, so you write list, not [].

The trap is that merely reading a missing key creates it. The line if groups["Abha"]: adds "Abha" with an empty list even though you were only asking. When you want to know whether a key exists, use in or .get().

02

Your task

Group students into by_city using defaultdict(list), with the city as the key and its students' names, in their original order, as the value. Then print each city with its students' names on one line.

Checks

5 checks
  1. Riyadh has three names in their original order
  2. Jeddah and Dammam have their names
  3. Three cities and no extra bucket
  4. by_city is a defaultdict(list)
  5. Each city was printed with its names on one line
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.