0
0
Pythonprogramming~15 mins

Dictionary comprehension with condition in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Dictionary Comprehension with Condition
๐Ÿ“– Scenario: You are managing a small bookstore's inventory. You have a list of books with their prices. You want to create a new dictionary that only includes books priced below a certain amount to plan a discount sale.
๐ŸŽฏ Goal: Build a dictionary comprehension with a condition to filter books priced below a set threshold.
๐Ÿ“‹ What You'll Learn
Create a dictionary called books with given book titles and prices.
Create a variable called max_price to set the price limit.
Use a dictionary comprehension with a condition to create a new dictionary called discount_books with books priced less than max_price.
Print the discount_books dictionary.
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Filtering products or items based on price or other conditions is common in online stores and inventory management.
๐Ÿ’ผ Career
Knowing how to filter dictionaries efficiently helps in data processing, reporting, and building features like price filters in apps.
Progress0 / 4 steps
1
Create the books dictionary
Create a dictionary called books with these exact entries: 'Python Basics': 45, 'Data Science 101': 60, 'Machine Learning': 55, 'Deep Learning': 70, 'AI for Beginners': 40.
Python
Need a hint?

Use curly braces {} to create a dictionary with keys as book titles and values as prices.

2
Set the maximum price
Create a variable called max_price and set it to 50.
Python
Need a hint?

Just assign the number 50 to the variable max_price.

3
Create filtered dictionary with comprehension
Use a dictionary comprehension to create a new dictionary called discount_books that includes only the books from books with prices less than max_price. Use for title, price in books.items() in your comprehension.
Python
Need a hint?

Use the format {key: value for key, value in dictionary.items() if condition} to filter.

4
Print the filtered dictionary
Print the discount_books dictionary using print(discount_books).
Python
Need a hint?

Use the print function to show the dictionary on the screen.