We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Organize Data

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.

Sorting Lists

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.

Assignment

    • It should accept a tuple[str, int] like ("b", 4868).
    • It should return the count value from the tuple.
    • It should accept the dict[str, int] returned by your character-counting function.
    • It should return a list[tuple[str, int]].
    • For each character, look up its count in the dictionary.
    • Append a tuple to the list, like ("b", 4868).
    • Use the built-in sorted() function.
    • Pass your sort_on helper as the key.
    • Use 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.

Tip

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.