0
0
Pythonprogramming~15 mins

Lambda with sorted() in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Sorting a List of Dictionaries Using Lambda with sorted()
๐Ÿ“– Scenario: You work in a small bookstore. You have a list of books, each with a title and a price. You want to organize the books by their price from lowest to highest so customers can easily see the cheapest books first.
๐ŸŽฏ Goal: Build a Python program that sorts a list of dictionaries representing books by their price using sorted() with a lambda function.
๐Ÿ“‹ What You'll Learn
Create a list called books with dictionaries containing 'title' and 'price' keys
Create a variable called sorted_books that sorts books by the 'price' key using sorted() and a lambda
Print the sorted_books list
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Sorting lists of dictionaries is common when working with data like products, books, or records where you want to order items by a specific detail.
๐Ÿ’ผ Career
Many jobs require sorting data efficiently. Using lambda with sorted() is a quick way to organize data without writing complex code.
Progress0 / 4 steps
1
Create the list of books
Create a list called books with these exact dictionaries: {'title': 'Book A', 'price': 12.99}, {'title': 'Book B', 'price': 8.99}, and {'title': 'Book C', 'price': 15.50}.
Python
Need a hint?

Use square brackets [] to create a list and curly braces {} for each dictionary.

2
Prepare to sort the books
Create a variable called sorted_books and set it to None for now. This will hold the sorted list later.
Python
Need a hint?

Just write sorted_books = None for now.

3
Sort the books by price using lambda with sorted()
Use sorted() with a lambda function to sort the books list by the 'price' key. Assign the result to sorted_books. Use lambda book: book['price'] as the key function.
Python
Need a hint?

Use sorted(books, key=lambda book: book['price']) to sort by price.

4
Print the sorted list of books
Print the sorted_books list to show the books sorted by price.
Python
Need a hint?

Use print(sorted_books) to show the sorted list.