Boss lesson · Unit 04
A gradebook
Averages, the best student, groups and a sorted report
What you practise
- A list of dictionaries: averages, the best student, grouping by grade, a sorted report
Try a question from this lesson
Pick one
A teacher keeps a gradebook: a list in which each student is a dictionary. What does this program show?
students = [
{"name": "Ada", "score": 92},
{"name": "Bo", "score": 67},
]
print(students[1]["name"])Hint
Read the square brackets from left to right: first a position in the list, then a key.
Correct answer
Bo
Why
students[1] is the second dictionary, the one for Bo. Then ["name"] looks up that key inside it. Reading from left to right, each pair of square brackets goes one level deeper.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
sum, max, min, sorted
Some jobs are so common that Python has them built in.
sum, max and min each take a list and hand back one value.
sorted hands back a new list in order, smallest first, and leaves the original list as it was.
scores = [92, 67, 81]
print(sum(scores)) # 240
print(max(scores)) # 92
print(sorted(scores)) # [67, 81, 92]
print(scores) # [92, 67, 81]Concept
Grouping
To sort items into groups, use a dictionary whose values are lists.
For each item, work out its group. If that key is new, start it with an empty list. Then append the item to its group's list.
A string can be indexed like a list: word[0] is its first character.
groups = {}
for word in ["ant", "bee", "ape"]:
key = word[0]
if key not in groups:
groups[key] = []
groups[key].append(word)
print(groups)
# {'a': ['ant', 'ape'], 'b': ['bee']}10 more exercises in the app
- 4× type the answer
- 2× fill the blanks
- 1× order the lines
- 2× multiple choice
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.