Intermediate · Working with data · topic 29 of 50 · 20 min
Sorting with key
Explanation
sorted() versus list.sort()
marks = [72, 45, 90, 61]
print(sorted(marks)) # new list
print(marks) # unchanged
marks.sort(reverse=True) # sorts marks itself
print(marks)Sorting with key
key is a function that Python calls on every item. It sorts the items by the values that function returns, but it moves the original items. key=len sorts by length; key=str.lower sorts without caring about capital letters.
names = ["meena", "Asha", "Ravi", "bhavya"]
print(sorted(names))
print(sorted(names, key=str.lower))
print(sorted(names, key=len))students = [("Asha", 82), ("Ravi", 67), ("Meena", 91)]
print(sorted(students, key=lambda s: s[1]))
print(sorted(students, key=lambda s: s[1], reverse=True))Sorting a dict by its values
sales = {"tea": 120, "coffee": 45, "lassi": 80}
ranked = sorted(sales.items(), key=lambda kv: kv[1], reverse=True)
print(ranked)
print(dict(ranked))
print(sorted(sales, key=sales.get))Two keys at once with a tuple
students = [("Ravi", 82), ("Asha", 91), ("Meena", 82)]
merit = sorted(students, key=lambda s: (-s[1], s[0]))
print(merit)operator.itemgetter
from operator import itemgetter
students = [("Asha", 82), ("Ravi", 67)]
print(sorted(students, key=itemgetter(1)))
products = [{"name": "Soap", "price": 40}, {"name": "Oil", "price": 180}]
print([p["name"] for p in sorted(products, key=itemgetter("price"))])Python sorting is stable
Stable means that items with equal keys keep their original order. If Asha came before Meena in the list and both have 82 marks, Asha still comes first after sorting by marks. This lets you sort in steps: sort by the less important key first, then by the more important one.
max and min with key
students = [("Asha", 82), ("Ravi", 67), ("Meena", 91)]
print(max(students, key=lambda s: s[1]))
print(min(["kiwi", "banana", "fig"], key=len))Watch the lesson
Sorting with key · 1/6
Sorting is everywhere: merit lists, cheapest products, top sellers. In this lesson you will sort by any rule you like.
Prefer a video by a teacher? Find free videos on “python sorted key lambda sorting tutorial” on YouTube ↗
In real life: Preparing a merit list
A school publishes a merit list: highest total first, and students with equal totals in alphabetical order. Principal Joseph also wants the topper and the student who needs the most help. One sorted call with a tuple key, plus max and min, does it all.
results = {"Ravi": 412, "Asha": 455, "Meena": 412, "Kabir": 389, "Zoya": 455}
merit = sorted(results, key=lambda name: (-results[name], name))
for rank, name in enumerate(merit, start=1):
print(rank, name, results[name])
print("Topper:", max(results, key=results.get))
print("Needs help:", min(results, key=results.get))Practice (0/3 done)
Write by_length(words) that returns a new list of the words sorted from shortest to longest. Words of the same length keep their original order.
Write merit_list(marks) where marks is a dict of name to marks. Return a list of names, highest marks first. When two students have the same marks, put their names in A to Z order.
Write cheapest(products) where products is a list of dicts like {"name": "Soap", "price": 40}. Return the name of the product with the lowest price. Use min with a key.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.