Sort list by multiple keys with tuple ordering in Python

Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

24 lines
Python 3.9+
def sort_multi_key(data):
    # Sorts by surname, then age, then score descending
    return sorted(
        data,
        key=lambda person: (
            person['surname'].lower(),
            person['age'],
            -person['score']  # negative to reverse sort by score
        )
    )


if __name__ == "__main__":
    people = [
        {'surname': 'Smith', 'age': 30, 'score': 88},
        {'surname': 'Smith', 'age': 30, 'score': 95},
        {'surname': 'Smith', 'age': 25, 'score': 78},
        {'surname': 'Jane', 'age': 30, 'score': 91},
        {'surname': 'Doe', 'age': 25, 'score': 85},
    ]

    sorted_people = sort_multi_key(people)
    for p in sorted_people:
        print(f"{p['surname']}, {p['age']}, {p['score']}")

Output

stdout
Doe, 25, 85
Jane, 30, 91
Smith, 25, 78
Smith, 30, 88
Smith, 30, 95

How it works

sorted() evaluates the key function once per item and sorts by the natural comparison of the returned tuple. Tuples compare element-by-element: Python moves to the next element only when the current ones are equal. Lowercasing the surname normalizes case-sensitive ordering. Negating the score inverts the order for that field, giving descending sort while the others stay ascending. This pattern keeps all sorting logic in one readable lambda, avoiding multiple passes.

Common mistakes

  • Forgetting to lowercase strings, causing case-sensitive order
  • Negating numeric fields you want ascending, inverting the order
  • Assuming `sorted` mutates the original list — it returns a new list
  • Using `reverse=True` to sort score descending, which also reverses every other field

Variations

  1. Use `operator.itemgetter` for a faster key when you don't need case normalization or negation
  2. Chain multiple sorts: sort by score descending first, then by age and surname for stability

Real-world use cases

  • Ranking products by category, stock, and price priority in an e‑commerce dashboard
  • Sorting employee directories by department, tenure, and salary for reporting
  • Ordering tournament standings by points, goal difference, and goals scored

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.