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.
- Start from a list of at least five scholarship dictionaries, each with a
nameand acountry. - Build a
by_countrydictionary where each key is a country and each value is a list of the scholarship names based there. - For each record: if the country isn't a key yet, start it with an empty list; then
appendthe name to that country's list. - Print each country with its scholarships using a
.items()loop.
- 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.
UK: Chevening, Gates Cambridge, Commonwealth
Germany: DAAD
USA: FulbrightWhere 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() loopHow we'll grade it
Four checks, four points. Three or above is passing — we'll ask you to revise anything we can't tick.
| Check | What we look for | Pt |
|---|---|---|
| It runs | Groups the records and prints them by country without crashing. | 1 |
| Values are lists | Each country key maps to a list of names, and countries that appear more than once collect all their names. | 1 |
| Nothing is lost or duplicated | Every scholarship lands under its country exactly once. The names across all lists match the original records. | 1 |
| Reads well | Each country is printed once, with its scholarships listed alongside it. | 1 |