Filtering & Sorting Data — Python

Filtering means taking the items that meet a condition. For a list students that holds dictionaries, you write [s["name"] for s in students if s["score"] >=…

Mrs. Rina is preparing the end-of-term announcement for class 8A. She needs three lists from the same data: the students who passed, the students who passed and came to class often, and the top three of the class. All three are made with two jobs: filtering (taking only the data that meets a condition) and sorting.

Filtering is like sifting rice: the grains that pass through the holes of the sieve are kept, the ones that do not are left behind. In Python, each grain is one item of a list, and the holes of the sieve are the if condition. Sorting is like lining students up for a class photo by height. You choose one thing to compare, for example height, then everyone is arranged by that thing. In Python, the thing to compare is written in key, one of the parameters of sorted.

Filtering with a comprehension

The data in this lesson is a list of dictionaries, one dictionary per student. In the List Comprehensions lesson, you filtered numbers with if. For a list of dictionaries, it works the same way. This code makes two lists:

students = [
    {"name": "Tono", "score": 88, "present": 15},
    {"name": "Budi", "score": 75, "present": 17},
    {"name": "Rina", "score": 92, "present": 20},
    {"name": "Dodi", "score": 64, "present": 19},
    {"name": "Sari", "score": 88, "present": 20},
]

passed = [s["name"] for s in students if s["score"] >= 75]
print(passed)

passed_and_present = [s["name"] for s in students if s["score"] >= 75 and s["present"] >= 18]
print(passed_and_present)

The output:

['Tono', 'Budi', 'Rina', 'Sari']
['Rina', 'Sari']

Sorting with sorted and key

In the Lambda lesson, you sorted menu items by price with key. Here key is not a dictionary key. For students, sort by score, from the highest:

ranked = sorted(students, key=lambda s: s["score"], reverse=True)
for s in ranked:
    print(s["name"], s["score"])

The output:

Rina 92
Tono 88
Sari 88
Budi 75
Dodi 64

Equal scores: a second comparison

Mrs. Rina's rule for equal scores: names go in alphabetical order, so Sari must come before Tono. For that, key returns a tuple with two things to compare: the first (the score), then the second (the name).

ranked = sorted(students, key=lambda s: (-s["score"], s["name"]))
print([s["name"] for s in ranked])

The output:

['Rina', 'Sari', 'Tono', 'Budi', 'Dodi']

The top N: cut, then number

Once sorted, the top three are the first three items: ranked[:3]. enumerate(..., start=1) from the For Loop lesson gives their places:

ranked = sorted(students, key=lambda s: (-s["score"], s["name"]))
for place, s in enumerate(ranked[:3], start=1):
    print(f"{place}. {s['name']:<5} {s['score']:>3}")

The output:

1. Rina   92
2. Sari   88
3. Tono   88

📌 Sorting a dictionary by value

Mr. Darto's sales dictionary can be sorted by how many of each item were sold. items() gives (item, count) pairs. In lambda p, p is one pair, so p[1] is the count:

sold = {"coffee with milk": 42, "sweet tea": 35, "toast": 18, "iced orange": 27}
ranked = sorted(sold.items(), key=lambda p: p[1], reverse=True)
print(ranked[:2])

The output:

[('coffee with milk', 42), ('sweet tea', 35)]

⚠️ An order that is reversed, and numbers sorted like text

TL;DR: Filtering means taking the items that meet a condition. For a list students that holds dictionaries, you write [s["name"] for s in students if s["score"] >= 75], and two conditions are joined with and. A filtered result keeps its original order. Sorting uses sorted(data, key=...). key is a function that gives the thing to compare, for example lambda s: s["score"], and reverse=True reverses the order. When two items are equal by key, sorted keeps their original order. For a second thing to compare, used when the first is equal, return a tuple: key=lambda s: (-s["score"], s["name"]) sorts scores from high to low, then names from A to Z. With a tuple key like this one, do not add reverse=True, because the names would be reversed too. In the sorted list ranked, ranked[:3] gives the top three, and enumerate(..., start=1) gives their places. Numbers stored as text must be compared as numbers, for example with key=int.

⚡ Filter with if

Write:

students = [
    {"name": "Tono", "score": 88, "present": 15},
    {"name": "Budi", "score": 75, "present": 17},
    {"name": "Rina", "score": 92, "present": 20},
    {"name": "Dodi", "score": 64, "present": 19},
    {"name": "Sari", "score": 88, "present": 20},
]

passed = [s["name"] for s in students if s["score"] >= 75]
print(passed)

passed_and_present = [s["name"] for s in students if s["score"] >= 75 and s["present"] >= 18]
print(passed_and_present)
Guess first: the second list only takes students whose score is 75 or more and who were present at least 18 times. Who is in it?

['Rina', 'Sari']. Tono passed but was present only 15 times, and Budi was present 17 times. Dodi was present 19 times, but his score is 64.

Meaning: A comprehension with if filters a list: only the items that meet the condition go into the result. The front part, s["name"], decides what is taken from each item. Two conditions are joined with and.

⚡ Sort with key

Write:

ranked = sorted(students, key=lambda s: s["score"], reverse=True)
for s in ranked:
    print(s["name"], s["score"])

Meaning: sorted sorts the students list from the step before. key (a parameter of sorted, not a dictionary key) gives the thing to compare: each student's score. reverse=True puts the highest score first. Tono and Sari both have 88. For equal values, sorted keeps the original order of the list. In students, Tono is written before Sari, so Tono still comes first.

⚡ A second comparison with a tuple

Guess first: key=lambda s: (-s["score"], s["name"]) returns a tuple: the score with a minus sign, then the name. Tuples are compared starting from their first item. Who comes first, Tono (88) or Sari (88)?

Sari. The first comparison, -88, is the same for both, so the second comparison decides: names from A to Z, and Sari comes before Tono.

Meaning: key can return a tuple. Python compares the first items first, and the second items are only looked at when the first ones are equal. The minus sign reverses the order of the numbers only, so scores go from high to low while names still go from A to Z. reverse=True would reverse both.

⚡ The top three

Meaning: Once sorted, ranked[:3] cuts out the first three items, and this slice gives no error if the list has fewer than three items. enumerate(ranked[:3], start=1) gives the places 1, 2, 3 for each item, ready to be printed as a list of winners.

What you will learn