Exercises
Nested Dictionaries
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print Ada's birth year and her first field.
Python
people = {"ada": {"born": 1815, "fields": ["maths", "computing"]}}
# print the year, then the first field
Chain the lookups: one bracket per level.
people = {"ada": {"born": 1815, "fields": ["maths", "computing"]}}
print(people["ada"]["born"])
print(people["ada"]["fields"][0])Exercise 2Passed
Look up a person who is not there, printing None instead of crashing.
Python
people = {"ada": {"born": 1815}}
# print the born value for alan, safely
The first get needs an empty dictionary as its default.
people = {"ada": {"born": 1815}}
print(people.get("alan", {}).get("born"))Exercise 3Passed
Group the names under their subject, creating each list as needed.
Python
pairs = [("maths", "ada"), ("maths", "grace"), ("computing", "katherine")]
groups = {}
# fill groups
print(groups)setdefault creates the list if the key is missing and returns it either way.
pairs = [("maths", "ada"), ("maths", "grace"), ("computing", "katherine")]
groups = {}
for subject, name in pairs:
groups.setdefault(subject, []).append(name)
print(groups)