Clients often want a list in a useful order: the cheapest products first, or names from A to Z. Python's sorted gives you a new, sorted list. It can't compare two dictionaries, though, so you tell it what to compare with a key function: a function that takes one item and returns the value to sort by.
def by_stars(review):
return review["stars"]
reviews = [{"user": "ana", "stars": 5}, {"user": "bo", "stars": 3}]
fewest_first = sorted(reviews, key=by_stars)
# [{"user": "bo", "stars": 3}, {"user": "ana", "stars": 5}]
Write key=by_stars without parentheses: you hand over the function itself, and sorted calls it on each item. sorted makes a new list, so the original list keeps its order.
The client picks the order with a query parameter: ?sort=price or ?sort=name. Any other value is a mistake, so the shop answers 400 with an error. Without sort, the list keeps the shop's order, and the filters still work. The lists below show product names only; each item is a full product.
GET /products?sort=price → 200 [Pen, Notebook, Mug, Lamp]
GET /products?sort=name → 200 [Lamp, Mug, Notebook, Pen]
GET /products → 200 [Mug, Notebook, Lamp, Pen]
GET /products?category=office&sort=price → 200 [Pen, Notebook]
GET /products?sort=color → 400 {"error": "Sort must be price or name"}
Your task: write two key functions, by_price and by_name. In GET /products, read sort, answer 400 for an unknown sort, and sort the filtered list by price or by name.
Assignment
Follow the Coding Tutorial to add sorting to GET /products.
Hint
Sort after the filter loop, so only the products that passed the filters get sorted. Give sorted the key function with key=, without parentheses.
Free plan: 30 tutor messages. PRO is unlimited.
