0
0
Rest APIprogramming~15 mins

Sort direction (asc, desc) in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Sort Direction (asc, desc) in REST API
📖 Scenario: You are building a simple REST API that returns a list of products. Users can choose to get the products sorted by price in ascending or descending order.
🎯 Goal: Create a small Python program that simulates sorting product data by price in ascending or descending order based on a configuration variable.
📋 What You'll Learn
Create a dictionary called products with product names as keys and prices as values.
Create a variable called sort_direction that can be either 'asc' or 'desc'.
Use a sorting method that sorts the products by price according to the sort_direction.
Print the sorted list of product names and prices.
💡 Why This Matters
🌍 Real World
Sorting data by ascending or descending order is common in APIs that return lists of items, like products, users, or events.
💼 Career
Understanding how to control sort direction helps you build flexible APIs and user interfaces that show data in the order users want.
Progress0 / 4 steps
1
Create the product data
Create a dictionary called products with these exact entries: 'apple': 120, 'banana': 80, 'cherry': 150, 'date': 100.
Rest API
Need a hint?

Use curly braces {} to create a dictionary with keys and values separated by colons.

2
Set the sort direction
Create a variable called sort_direction and set it to the string 'asc' to sort prices in ascending order.
Rest API
Need a hint?

Assign the string 'asc' to the variable sort_direction.

3
Sort the products by price
Create a variable called sorted_products that sorts the items of products by price. Use sort_direction to decide ascending or descending order. Use sorted(products.items(), key=lambda item: item[1], reverse=sort_direction == 'desc').
Rest API
Need a hint?

Use the sorted() function with key=lambda item: item[1] to sort by price. Set reverse=True if sort_direction is 'desc'.

4
Print the sorted products
Print the sorted_products list to show the product names and prices in the chosen order using print(sorted_products).
Rest API
Need a hint?

Use print() to show the sorted list.