Mastering Python’s sorted() and key Parameter: From Basics to Advanced Practical Applications

  • Home
  • Mastering Python’s sorted() and key Parameter: From Basics to Advanced Practical Applications

During web application development, system data processing, or data analysis, sorting is a continuous operation. Python provides an extremely powerful built-in sorted() function, but its true power is only unlocked when you master the key parameter.

This article from DCSoftTech will provide a detailed guide to the syntax, underlying principles, and the 5 most common practical application cases of sorted() combined with the key parameter.

1. Overview of the sorted() Function in Python

The sorted() function accepts any iterable data structure (such as Lists, Tuples, Dictionaries, etc.) and returns a new sorted list. This helps preserve the original data (avoiding side effects).

Basic Syntax

Python

sorted(iterable, key=None, reverse=False)
  • iterable: The sequence, list, tuple, dictionary, set, etc., to be sorted.

  • key: A function that takes a single element from the iterable and returns a value used as the sorting “criterion.”

  • reverse: False (default – ascending order) or True (descending order).

Difference Between sorted() and list.sort()

  • list.sort() only applies to list objects, modifies the original list directly (in-place), and returns None.

  • sorted() applies to any iterable, creates a new list, and leaves the original data unaffected.

2. How Does the key Parameter Work?

When you pass key=function_name, Python does the following:

  1. Applies function_name to each element in the list.

  2. Takes the return value from that function as the comparison key (Sort Key).

  3. Sorts the elements based on the order of these keys.

You can pass a built-in function (such as len, str.lower), a custom function defined using def, a lambda function, or a function from the operator library.

3. 5 Practical Data Sorting Techniques with sorted() + key

Case 1: Sorting Strings by Length or Case-Insensitively

By default, Python sorts strings according to the ASCII table (uppercase letters come before lowercase letters). Thanks to the key parameter, you can customize this to your desired logic.

Example 1: Sorting a list of names by length

Python

names = ["Nguyen Van A", "Le B", "Tran Thi Minh C", "Do D"]

# Sort from shortest to longest
sorted_names = sorted(names, key=len)
print(sorted_names)
# Output: ['Do D', 'Le B', 'Nguyen Van A', 'Tran Thi Minh C']

Example 2: Case-insensitive sorting

Python

brands = ["apple", "Samsung", "Xiaomi", "ASUS"]

# Case-insensitive sort
sorted_brands = sorted(brands, key=str.lower)
print(sorted_brands)
# Output: ['apple', 'ASUS', 'Samsung', 'Xiaomi']

Case 2: Sorting a List of Dictionaries by a Specific Key (Working with APIs/Databases)

When receiving JSON data from an API or querying a database, data is often in the form of List[Dict].

Requirement: Sort a list of employees by age in ascending order.

Python

employees = [
    {"name": "Dung", "age": 28, "salary": 1500},
    {"name": "An", "age": 22, "salary": 1200},
    {"name": "Binh", "age": 35, "salary": 2000},
]

# Use a lambda function as the key
sorted_by_age = sorted(employees, key=lambda emp: emp["age"])

print(sorted_by_age)
# Output:
# [
#   {'name': 'An', 'age': 22, 'salary': 1200},
#   {'name': 'Dung', 'age': 28, 'salary': 1500},
#   {'name': 'Binh', 'age': 35, 'salary': 2000}
# ]

Performance Optimization: For large datasets, instead of using a lambda function, you should use itemgetter from the operator module for faster execution.

Python

from operator import itemgetter

sorted_by_salary = sorted(employees, key=itemgetter("salary"), reverse=True)

Case 3: Multiple Criteria Sorting

In practice, you often need to sort by a primary criterion first, and if values are equal, sort by a secondary criterion.

Requirement: Sort students by Score in descending order; if scores are equal, sort by Name in ascending order (A–Z).

This example returns a tuple (-student["score"], student["name"]) inside the key function:

  • The negative sign -student["score"] reverses the numerical order, placing higher scores first.

  • The name remains a normal string to sort alphabetically.

Python

students = [
    {"name": "Minh", "score": 8.5},
    {"name": "An", "score": 9.0},
    {"name": "Hoa", "score": 8.5},
    {"name": "Binh", "score": 9.0},
]

# Prioritize score descending (-), then name ascending (+)
sorted_students = sorted(students, key=lambda s: (-s["score"], s["name"]))

for s in sorted_students:
    print(f"{s['name']}: {s['score']}")

# Output:
# An: 9.0
# Binh: 9.0
# Hoa: 8.5
# Minh: 8.5

Case 4: Sorting a List of Class Objects (Object-Oriented Programming)

When writing OOP code, your data consists of instances of a class. You can use key or attrgetter to sort them.

Python

from operator import attrgetter

class Product:
    def __init__(self, name, price, stock):
        self.name = name
        self.price = price
        self.stock = stock

    def __repr__(self):
        return f"Product({self.name}, Price: {self.price}, Stock: {self.stock})"

products = [
    Product("Laptop", 1200, 10),
    Product("Mouse", 25, 50),
    Product("Keyboard", 75, 20),
]

# Sort product list by price in ascending order
sorted_products = sorted(products, key=attrgetter("price"))

print(sorted_products)
# Output: [Product(Mouse, Price: 25, Stock: 50), Product(Keyboard, Price: 75, Stock: 20), Product(Laptop, Price: 1200, Stock: 10)]

Case 5: Sorting a Dictionary by Value or Custom Key

Dictionaries in Python (3.7+) maintain insertion order. To sort a dictionary by its values, combine sorted() with .items().

Requirement: Game score leaderboard, sorted from highest score to lowest.

Python

leaderboard = {"player_A": 450, "player_B": 1200, "player_C": 890, "player_D": 1200}

# sorted() returns a list of (key, value) tuples
sorted_tuples = sorted(leaderboard.items(), key=lambda item: item[1], reverse=True)

# Convert back to a Dictionary
sorted_leaderboard = dict(sorted_tuples)

print(sorted_leaderboard)
# Output: {'player_B': 1200, 'player_D': 1200, 'player_C': 890, 'player_A': 450}

4. DCSoftTech Best Practices & Notes When Using the key Parameter

  1. Prioritize operator.itemgetter / attrgetter for Large Datasets: Functions in the operator module offer better performance (C-speed) compared to calling lambda functions on datasets with hundreds of thousands of records.

  2. Use the Minus Sign (-) Technique for Numeric Data: When performing multi-criteria sorting with mixed ascending and descending requirements, use the negative sign for numeric fields (int, float).

  3. Stable Sort: Python uses the Timsort algorithm. It ensures that if two elements share the same key value, their original relative order is preserved.

  4. Avoid Heavy Logic Inside the key Function: The key function executes $N$ times (where $N$ is the number of elements). Avoid database queries or API calls inside the key function.

Conclusion

Mastering the sorted() function and the key parameter will help you write cleaner, more elegant, and highly optimized Python source code. From basic list sorting to handling complex data structures in real-world projects, sorted() remains a top-tier tool.

We hope this Python tip article from DCSoftTech proves useful for your programming workflow!

Categories:

Leave Comment

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30