Python Tip: Sorting with key=

Sort values by the detail that matters

Learn how to customize Python sorting with the key and reverse arguments.
Author

Shep Bryan IV

Python Tip: sorted()

Need to sort a list?
Need to sort it a specific way?
Use sorted() with the key argument to choose the how to sort it.

Basic Sorting

sorted() returns a new list with the values in order.

scores = [88, 73, 95, 82]

sorted_scores = sorted(scores)

print("Original:", scores)
print("Sorted:", sorted_scores)
Original: [88, 73, 95, 82]
Sorted: [73, 82, 88, 95]

The original list stays unchanged.

Sort Words by Length

By default, strings are sorted alphabetically. Use key= to choose a different thing to sort by, like the length of each string.

words = ["pear", "fig", "watermelon"]

alphabetical = sorted(words)
by_length = sorted(words, key=len)  # Sort by length

print("Alphabetical:", alphabetical)
print("By length:", by_length)
Alphabetical: ['fig', 'pear', 'watermelon']
By length: ['fig', 'pear', 'watermelon']

Sort Without Case Sensitivity

Capital letters normally sort before lowercase letters. Use str.lower to compare lowercase versions of each word!

names = ["grace", "Ada", "linus", "Guido"]

default = sorted(names)
ignore_case = sorted(names, key=str.lower)

print("Default:", default)
print("Ignore case:", ignore_case)
Default: ['Ada', 'Guido', 'grace', 'linus']
Ignore case: ['Ada', 'grace', 'Guido', 'linus']

Sort Dictionaries

Use a lambda function to choose the thing to sort by, like a value from a dictionary.

people = [
    {"name": "Ada", "age": 36},
    {"name": "Guido", "age": 31},
    {"name": "Grace", "age": 28},
]

by_age = sorted(people, key=lambda p: p["age"])

for p in by_age:
    print(p["name"], p["age"])
Grace 28
Guido 31
Ada 36

Reverse the Order

Add reverse=True when you want the largest value first.

scores = [88, 73, 95, 82]

highest_first = sorted(scores, reverse=True)

print(highest_first)
[95, 88, 82, 73]

You can combine reverse=True with key= too.

Wrap-Up

Now you can customize how Python sorts lists!

Use sorted() to create a new sorted list.

Use key= to choose how Python sorts your list.

Add reverse=True when you want descending order.

Follow me for more tips.
Shep Bryan IV