PYTHON

Custom Sorting of Lists of Dictionaries or Objects in Python

Master custom sorting in Python by using the `key` argument with `sort()` or `sorted()` to order lists of dictionaries or custom objects by specific attributes, enhancing data presentation.

users = [
    {"name": "Alice", "age": 30, "score": 95},
    {"name": "Bob", "age": 24, "score": 88},
    {"name": "Charlie", "age": 30, "score": 92},
    {"name": "David", "age": 28, "score": 95}
]

# Sort by 'age' (ascending)
sorted_by_age = sorted(users, key=lambda user: user['age'])
print("Sorted by Age:")
for user in sorted_by_age: print(user)

# Sort by 'score' (descending)
sorted_by_score_desc = sorted(users, key=lambda user: user['score'], reverse=True)
print("
Sorted by Score (descending):")
for user in sorted_by_score_desc: print(user)

# Sort by multiple criteria: 'age' (ascending), then 'score' (descending)
# The lambda function returns a tuple; sorting is done element-wise.
# For descending score, we negate the score or use operator.itemgetter with reverse=True
sorted_by_age_score = sorted(users, key=lambda user: (user['age'], -user['score']))
print("
Sorted by Age (asc), then Score (desc):")
for user in sorted_by_age_score: print(user)

# Example with custom objects
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price
    def __repr__(self):
        return f"Product(name='{self.name}', price={self.price})"

products = [
    Product("Laptop", 1200),
    Product("Mouse", 25),
    Product("Keyboard", 75),
    Product("Monitor", 300)
]

sorted_products_by_price = sorted(products, key=lambda p: p.price)
print("
Sorted Products by Price:")
for p in sorted_products_by_price: print(p)
How it works: Python's `list.sort()` method and `sorted()` built-in function allow for powerful custom sorting using the `key` argument. By passing a function (often a `lambda` function) to `key`, you can specify a value to be used for comparison instead of the original item itself. This is incredibly useful for sorting lists of dictionaries by a specific key's value, or lists of custom objects by one of their attributes. For multi-criteria sorting, the `key` function can return a tuple, and Python will sort by the first element, then the second, and so on. Negating numerical values in the tuple allows for mixed ascending/descending sorting.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs