PYTHON
Custom Sorting Lists of Complex Objects/Tuples using `key` Argument
Master custom sorting in Python using the `key` argument with `list.sort()` or `sorted()`. Sort lists of dictionaries, objects, or tuples by specific attributes or computed values.
# Sorting a list of tuples by the second element
data_tuples = [("apple", 5), ("orange", 2), ("banana", 8), ("grape", 1)]
sorted_by_count = sorted(data_tuples, key=lambda x: x[1])
print(f"Sorted by count (tuple): {sorted_by_count}")
# Sorting a list of dictionaries by a specific key
data_dicts = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
]
sorted_by_age = sorted(data_dicts, key=lambda x: x["age"])
print(f"Sorted by age (dict): {sorted_by_age}")
# Sorting a list of objects by an attribute
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)
]
sorted_products_by_price = sorted(products, key=lambda p: p.price)
print(f"Sorted products by price: {sorted_products_by_price}")
# Reverse sorting
sorted_products_by_price_desc = sorted(products, key=lambda p: p.price, reverse=True)
print(f"Sorted products by price (desc): {sorted_products_by_price_desc}")
How it works: Python's `sorted()` function and `list.sort()` method accept a `key` argument, which is a function that extracts a comparison key from each element in the iterable. This allows for highly flexible custom sorting. Instead of comparing the elements directly, the `key` function's return value is used for comparison. This snippet demonstrates sorting lists of tuples, dictionaries, and custom objects based on specific elements, keys, or attributes, including reverse sorting.