Why dictionary comprehension is used
๐ Scenario: Imagine you have a list of fruits with their prices, and you want to create a new dictionary that only includes fruits costing less than $2. Instead of writing many lines of code, dictionary comprehension helps you do this quickly and clearly.
๐ฏ Goal: Build a small program that uses dictionary comprehension to filter fruits by price, showing how dictionary comprehension makes the code simple and easy to read.
๐ What You'll Learn
Create a dictionary called
fruits with exact entries: 'apple': 1.5, 'banana': 0.8, 'cherry': 2.5, 'date': 3.0, 'elderberry': 1.2Create a variable called
max_price and set it to 2Use dictionary comprehension with
fruit and price to create a new dictionary called affordable_fruits that includes only fruits with price less than max_pricePrint the
affordable_fruits dictionary๐ก Why This Matters
๐ Real World
Filtering and transforming data quickly is common in real-world programs, like showing only affordable products in a store.
๐ผ Career
Knowing dictionary comprehension helps you write clean, efficient code, a skill valued in many programming jobs.
Progress0 / 4 steps