PYTHON
Sorting Lists of Custom Objects by Attributes using `key`
Learn to sort lists containing custom Python objects or dictionaries based on specific attributes or keys using the `sort()` method or `sorted()` function with a `key` argument for structured data.
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, 5),
Product("Mouse", 25, 50),
Product("Keyboard", 75, 15),
Product("Monitor", 300, 10)
]
# Sort by price (ascending)
sorted_by_price = sorted(products, key=lambda p: p.price)
print(f"Sorted by price: {sorted_by_price}")
# Sort by stock (descending)
sorted_by_stock_desc = sorted(products, key=lambda p: p.stock, reverse=True)
print(f"Sorted by stock (desc): {sorted_by_stock_desc}")
# Sort by name (alphabetically)
products.sort(key=lambda p: p.name) # In-place sort
print(f"Sorted by name (in-place): {products}")
# Example with a list of dictionaries
users = [
{"name": "Charlie", "age": 25},
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 22}
]
sorted_users_by_age = sorted(users, key=lambda u: u["age"])
print(f"Sorted users by age: {sorted_users_by_age}")
How it works: When working with lists of custom objects or dictionaries, Python's `sorted()` function and list's `sort()` method allow you to specify a `key` argument. This `key` is a function that extracts a comparison key from each element in the iterable. Common practice is to use a `lambda` function to define this key inline, such as `lambda p: p.price` to sort `Product` objects by their `price` attribute. The `reverse=True` argument can be used for descending order.