0
0
Pythonprogramming~15 mins

Why dictionary comprehension is used in Python - See It in Action

Choose your learning style9 modes available
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.2
Create a variable called max_price and set it to 2
Use dictionary comprehension with fruit and price to create a new dictionary called affordable_fruits that includes only fruits with price less than max_price
Print 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
1
Create the initial dictionary of fruits and prices
Create a dictionary called fruits with these exact entries: 'apple': 1.5, 'banana': 0.8, 'cherry': 2.5, 'date': 3.0, 'elderberry': 1.2
Python
Need a hint?

Use curly braces {} to create the dictionary and separate each fruit-price pair with commas.

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

Just write max_price = 2 on a new line.

3
Use dictionary comprehension to filter affordable fruits
Use dictionary comprehension with variables fruit and price to create a new dictionary called affordable_fruits that includes only fruits with price less than max_price
Python
Need a hint?

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

4
Print the filtered dictionary
Write print(affordable_fruits) to display the dictionary of fruits with price less than max_price
Python
Need a hint?

Use print(affordable_fruits) to show the result.