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']
[s["name"] for s in students if s["score"] >= 75]reads: for each students, if the score is 75 or more, take the name.- The front part,
s["name"], decides what goes into the result list. Write justsif you want the whole dictionary. - Two conditions are joined with
and: a student must pass and be present at least 18 times. Tono passed, but was present only 15 times, so he is not in the second list. - The result keeps the order of the
studentslist. Filtering does not sort.
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
key=lambda s: s["score"]tellssortedwhat to compare: each student's score.reverse=Truereverses the order, so the highest score comes first.- Tono and Sari both have 88. For equal values,
sortedkeeps the original order of the list, and Tono is written first in thestudentslist. So Tono is shown before Sari.
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']
- Python compares tuples by their first item. The second item is only looked at when the first items are equal.
-s["score"]is the score with a minus sign. Withoutreverse,sortedsorts from small to large. Sorting -92, -88, -75 from small to large gives the same order as sorting 92, 88, 75 from large to small. So the minus sign reverses the order of the scores only.s["name"]still goes from A to Z. That is why this code uses the minus sign and notreverse=True:reversewould reverse the names too, so Tono would be in front of Sari again.
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
ranked[:3]cuts out the first three items. If the list has fewer than three items, this slice gives no error: the result is every item of that list.:<5makes the name take 5 characters of space, left-aligned, and:>3makes the score take 3 characters of space, right-aligned. The result is straight columns.- Inside this f-string, the dictionary key is written with single quote marks,
s['name'], because the f-string itself uses double quote marks.
📌 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
reverse=Truewith a tuple key.reversereverses every comparison, names included. To reverse a number only, put a minus sign on the number.- Keeping the result of
.sort().ranked = scores.sort()makesrankedholdNone, because.sort()sorts the list itself and returns nothing. Usesorted(...)when you need a new list. - Numbers stored as text. Values from a CSV are strings, and strings are sorted letter by letter:
sorted(["100", "99", "250"])gives['100', '250', '99']. Compare them as numbers withint. For example,key=intturns each string into a number only for the comparison, so the result is['99', '100', '250']. The items of the list are still strings. - Capital letters first.
sorted(["Zaki", "ani", "Budi"])gives['Budi', 'Zaki', 'ani'], because all capital letters are sorted before small letters.key=str.lowercompares the small-letter version:['ani', 'Budi', 'Zaki'].
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.