PYTHON INTERMEDIATEChapter 6 · Comprehensions and data tools
Sorting with keys and lambda
sorted() and .sort() accept a key function that turns each item into the value to sort by. A lambda is a tiny one-line function without a name: lambda s: s["mag"] takes an item and returns its magnitude. Add reverse=True for largest first. min() and max() accept the same key.
Worked example
How it reads
key=is called once per item; the list is ordered by what it returnslambda s: s["mag"]is the same as a smalldefthat returnss["mag"]- Built-ins like
lencan be keys too:key=len

Cloud tip: To sort by two things, return a tuple:
key=lambda p: (p["team"], p["score"]).

