Exercises
Dictionary Methods
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Group each name under its subject, creating the list when the subject is new.
Python
pairs = [("maths", "ada"), ("maths", "grace"), ("code", "kat")]
groups = {}
# fill groups
print(groups)setdefault returns the existing list, or stores and returns a new one.
pairs = [("maths", "ada"), ("maths", "grace"), ("code", "kat")]
groups = {}
for subject, name in pairs:
groups.setdefault(subject, []).append(name)
print(groups)Exercise 2Passed
This raises because the view is live. Fix it so the low scores are removed.
Python
scores = {"a": 1, "b": 5, "c": 2}
for key in scores:
if scores[key] < 3:
del scores[key]
print(scores)Loop over a snapshot of the keys instead.
scores = {"a": 1, "b": 5, "c": 2}
for key in list(scores):
if scores[key] < 3:
del scores[key]
print(scores)Exercise 3Passed
Merge the custom settings over the defaults, leaving both originals unchanged.
Python
defaults = {"colour": "black", "size": 10}
custom = {"size": 12}
# print the merged result, then the untouched defaults
The | operator builds a new dictionary.
defaults = {"colour": "black", "size": 10}
custom = {"size": 12}
print(defaults | custom)
print(defaults)