PYTHON

Sorting Custom Objects by Multiple Attributes

Sort lists of custom Python objects using `key` functions and `itemgetter` for multi-attribute sorting, handling ascending and descending orders.

import operator

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

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

products = [
    Product('Laptop', 1200, 50),
    Product('Mouse', 25, 200),
    Product('Keyboard', 75, 100),
    Product('Monitor', 300, 50),
    Product('Webcam', 50, 200)
]

# 1. Sort by a single attribute (price) using a lambda function
products_by_price = sorted(products, key=lambda p: p.price)
print(f"
Sorted by price (asc):
{products_by_price}")

# 2. Sort by a single attribute (stock) in descending order
products_by_stock_desc = sorted(products, key=lambda p: p.stock, reverse=True)
print(f"
Sorted by stock (desc):
{products_by_stock_desc}")

# 3. Sort by multiple attributes (price then name) using a lambda function
# Default is ascending for each attribute
products_by_price_then_name = sorted(products, key=lambda p: (p.price, p.name))
print(f"
Sorted by price (asc) then name (asc):
{products_by_price_then_name}")

# 4. Sort by multiple attributes using operator.attrgetter (more efficient for many items)
# Sort by stock (desc) then price (asc)
products_by_stock_desc_then_price = sorted(
    products, 
    key=lambda p: (-p.stock, p.price) # Negate stock for descending order
)
print(f"
Sorted by stock (desc) then price (asc) using lambda with negation:
{products_by_by_stock_desc_then_price}")

# Alternative with operator.attrgetter for multiple attributes (requires a bit more logic for mixed asc/desc)
# For simple multi-attribute sorting (all asc or all desc) attrgetter is great.
# For mixed, lambda with negation is often cleaner.
products_by_price_then_stock = sorted(products, key=operator.attrgetter('price', 'stock'))
print(f"
Sorted by price (asc) then stock (asc) using attrgetter:
{products_by_price_then_stock}")
How it works: This snippet demonstrates how to sort a list of custom Python objects, a common requirement in web development for displaying ordered data. Python's `sorted()` function and `list.sort()` method accept a `key` argument, which is a function that extracts a comparison key from each list element. We use `lambda` functions to specify single or multiple attributes for sorting. For multi-attribute sorting, providing a tuple of attributes as the key allows Python to sort based on the first attribute, then the second for ties, and so on. To sort in descending order for a numeric attribute, you can negate its value within the `lambda` function's tuple.

Need help integrating this into your project?

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

Hire DigitalCodeLabs