AssignmentsWeek 02 · Organizing dataGroup scholarships by country
wk02.p19Practice exerciseWeek 02 · Organizing dataOpen · due this week

Group scholarships by country

Turn a flat list of scholarship records into a dictionary that groups them by country. The 'group by' pattern — a dictionary whose values are lists — that you'll use on real data forever.

What you'll build

Turn a flat list of scholarship records into a dictionary that groups them by country. The 'group by' pattern — a dictionary whose values are lists — that you'll use on real data forever.

Requirements

The must-do parts. If any are missing, we'll ask you to take another pass.

  1. Start from a list of at least five scholarship dictionaries, each with a name and a country.
  2. Build a by_country dictionary where each key is a country and each value is a list of the scholarship names based there.
  3. For each record: if the country isn't a key yet, start it with an empty list; then append the name to that country's list.
  4. Print each country with its scholarships using a .items() loop.
Bonus, if you're feeling brave
  • Replace the if-check with by_country.setdefault(country, []).append(name) and make sure you get the same result.
  • After grouping, print which country has the most scholarships.

Examples

What your program should look like when it runs. Lines starting with $ are typed by you; the rest is your program.

Example cell runs
UK: Chevening, Gates Cambridge, Commonwealth
Germany: DAAD
USA: Fulbright

Where to start

Copy this scaffold into a new file. You don't have to use it — it's just a friendly nudge.

# Group scholarships by country

scholarships = [
    {"name": "Chevening", "country": "UK"},
    {"name": "Gates Cambridge", "country": "UK"},
    {"name": "DAAD", "country": "Germany"},
    {"name": "Fulbright", "country": "USA"},
    {"name": "Commonwealth", "country": "UK"},
]

by_country = {}

# TODO: for each scholarship, make sure its country has a list,
#       then append the name to that list

# TODO: print each country and its scholarships with a .items() loop

How we'll grade it

Four checks, four points. Three or above is passing — we'll ask you to revise anything we can't tick.

CheckWhat we look forPt
It runsGroups the records and prints them by country without crashing.1
Values are listsEach country key maps to a list of names, and countries that appear more than once collect all their names.1
Nothing is lost or duplicatedEvery scholarship lands under its country exactly once. The names across all lists match the original records.1
Reads wellEach country is printed once, with its scholarships listed alongside it.1
Ready?
Hand it in
You can submit a draft and revise later if you're not done.
Begin submission →