AI Hints
Home›DSA in Python Tutorial›Quick Sort and Keys
DSA in Python · Lesson 56 of 132

Sorting with key

Sort by anything.

⏱ 2 min read▶ Video at 1:05:35🎓 Free
Watch this lesson in the DSA in Python courseWatch on YouTube ↗Full DSA in Python course

Real data is rarely just numbers. You sort people by age, words by length, and products by price. Python's sorted takes a key function, which tells it what to compare.

Sorting with key
From the video: Sorting with key
  • People by age
  • Words by length
  • Products by price

Keys for every job

Key equals len sorts words by their length. A lambda can pull out any field, like the price from each product. And a tuple key sorts by one thing, then another. Here, by category first, then by price from high to low, using a minus sign. We print just the names. Run it.

keys.pypython
words = ["kiwi", "banana", "fig", "apple"]
print(sorted(words, key=len))

products = [("pen", "office", 3), ("desk", "office", 120),
            ("mug", "kitchen", 8), ("kettle", "kitchen", 25)]
print([p[0] for p in sorted(products, key=lambda p: p[2])])
print([p[0] for p in sorted(products, key=lambda p: (p[1], -p[2]))])
Output
['fig', 'kiwi', 'apple', 'banana']
['pen', 'mug', 'kettle', 'desk']
['kettle', 'mug', 'desk', 'pen']

Key tips

The key function runs once per item, so it's efficient. Use reverse equals true to flip the order. Operator dot item getter is a fast alternative to a lambda. And min and max accept a key too, like the cheapest product, or the longest word.

keyvalue
key=lenby length
key=lambda p: p[2]by a field
(a, -b)two levels
min / maxtake key too

Summary

A key function tells Python what to compare. Use tuples for several levels. Next, stability, and why it matters.

Key takeaways
  • key=
  • lambda
  • tuples for ties
Next up: Stable Sorting — keeping ties in order