Start learning free

LESSON 28 OF 188 · BACKEND: YOUR FIRST API

Sort the List in Python

Practice

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.


STEP 1 OF 11
    Ctrl + Enter to check

    Shop Sort in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free