Editor

Sort by Multiple Criteria

Advanced · Write the code · from Python Sorting: sort(), sorted(), Key Functions, and Custom Order

From the lesson: Python Sorting: sort(), sorted(), Key Functions, and Custom Order

Imagine your bookshelf at home. Books are scattered everywhere - some by title, some by color, some shoved in sideways. Finding anything takes forever.

Read the lesson

Sort the list of products first by category (alphabetically), then by price (lowest first) within each category.

Print each product on a separate line in the format: category: name - $price

products = [
{'name': 'Banana', 'category': 'fruit', 'price': 1.20},
{'name': 'Milk', 'category': 'dairy', 'price': 3.50},
{'name': 'Apple', 'category': 'fruit', 'price': 0.80},
{'name': 'Cheese', 'category': 'dairy', 'price': 5.00},
{'name': 'Cherry', 'category': 'fruit', 'price': 4.00},
{'name': 'Yogurt', 'category': 'dairy', 'price': 2.50},
]
# Sort by category, then by price within each category

More Sorting exercises

All Python exercises · 50 practice problems · Data Structures quiz