Transforming and Combining Data · practice
Sort Records with a Key
The previous lesson combined prompts and responses into complete attempt records. Once records belong together, a program can order them without separating their fields again.
In Chapter 2, you passed a named sorted to rank attempts by one
def score_of(attempt):
return attempt["score"]
ranked = sorted(attempts, key=score_of, reverse=True)
That ranking leaves an open question: what should happen when two learners have the same score? We need a second rule so higher scores come first and equal scores are resolved by less time.
Tuple keys provide priorities
Python compares
(1, 40) < (2, 10)
The first values decide this comparison. A later value matters only when earlier values are equal.
A sorting key can return two values. For example, tasks can be ordered by higher priority first, then by shorter duration:
def task_key(task):
return (-task["priority"], task["minutes"])
Then sort in the normal ascending direction:
sorted(tasks, key=task_key)
Negating the priority places larger priorities first because -9 comes before -8. Minutes remain positive, so shorter tasks come first when priorities match. The exercise transfers this pattern to scores and completion times.
The tuple clearly states the priority:
priority descending;
minutes ascending.
Which record comes first with the key (-score, seconds)?
Implement a two-rule ranking
Complete the key and ranking functions. sorted must return a new
Task
Complete both
ranking_key(attempt)returns(-score, seconds).rank_attempts(attempt_list)returnssorted(attempt_list, key=ranking_key).Do not use
reverse=True, because the twofields use different directions. Do not modify the original
.