

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Organize Data
incomplete
2: Print a Report
incomplete
3: Arguments
incomplete
This lesson's interactive features are locked, please to keep using them
Right now, our character counts are stored in a dictionary. That's perfect for counting, but the final report needs the characters ordered from most common to least common.
To do that, we'll convert the dictionary into a list of (character, count) tuples, then sort the list by count.
You can use the built-in sorted() function to sort a list. It returns a new sorted list:
counts = [7, 10, 2]
sorted_counts = sorted(counts)
print(sorted_counts)
# [2, 7, 10]
If you want the biggest values first, use reverse=True:
counts = [7, 10, 2]
sorted_counts = sorted(counts, reverse=True)
print(sorted_counts)
# [10, 7, 2]
For BookBot, we're not sorting a simple list of integers. We're sorting a list of tuples, and we want to sort by the count inside each tuple. We can control how sorted() compares items by passing a helper function to the key parameter:
def sort_on(vehicle: tuple[str, int]) -> int:
return vehicle[1]
vehicle_counts = [("car", 7), ("plane", 10), ("boat", 2)]
sorted_vehicle_counts = sorted(vehicle_counts, reverse=True, key=sort_on)
print(sorted_vehicle_counts)
# [('plane', 10), ('car', 7), ('boat', 2)]
The key=sort_on part tells sorted() to call sort_on for each tuple and use the returned value for comparison. In this example, that means we're sorting by the number at index 1 in each tuple.
tuple[str, int] like ("b", 4868).dict[str, int] returned by your character-counting function.list[tuple[str, int]].("b", 4868).sorted() function.sort_on helper as the key.reverse=True.For now, print the raw sorted list of tuples. You'll format it into the final report in the next lesson.
Run and submit the CLI tests from the root of your project.
When sorting tuples, Python normally compares the first value first, then the second value if there's a tie. So we could store our data as (count, character) and sort it without a key:
chars = [
(4868, "b"),
(44538, "e"),
(25894, "a"),
]
print(sorted(chars, reverse=True))
# [(44538, 'e'), (25894, 'a'), (4868, 'b')]
For BookBot, we'll keep each tuple as (character, count) because that shape is easier to read. The key=sort_on argument lets us sort by count without rearranging the data to fit Python's default tuple sorting behavior.