Python Programming Challenge #6 - Making Dictionaries of Filtered Items
Master Python Dictionary Filtering and Data Manipulation
This programming challenge focuses on filtering dictionaries based on multiple criteria while dynamically adding new key-value pairs during processing.
Core Concepts Covered
Dictionary Access
Learn to access nested dictionary values using square bracket notation. Essential for working with structured data in Python.
Filtering Operations
Apply multiple conditional filters to select items based on price range and stock availability criteria.
Dynamic Key Addition
Add calculated fields on-the-fly by creating new dictionary keys with computed values during iteration.
Implementation Process
Initialize Empty List
Create a new list called medium_priced_fruits to store filtered results
Iterate Through Dictionary List
Loop through each fruit dictionary in the original fruit_list collection
Apply Price Filter
Check if price per pound is between 1 and 2 dollars inclusive
Check Stock Status
Verify that the in stock value is true before including the item
Calculate Total Price
Add new total price key by multiplying pounds times price per pound
Append to Results
Add the modified dictionary to the medium_priced_fruits list
Use fruit_list[0]["fruit"] syntax to access dictionary values. The first bracket specifies the list index, the second specifies the dictionary key.
Filter Criteria Checklist
Ensures minimum price threshold for medium-priced category
Maintains upper limit for medium-priced classification
Filters out unavailable items from the results
Add computed field showing total cost for the quantity
Before vs After Processing
| Feature | Original Dictionary | Filtered Dictionary |
|---|---|---|
| Keys | fruit, lbs, price per lb, in stock | fruit, lbs, price per lb, in stock, total price |
| Price Range | All prices | $1.00 - $2.00 only |
| Stock Status | All items | In stock only |
| Calculations | None | Total price computed |
We will also add a new key on the fly, called total price, which will be a math calculation of the pounds times the price per pound.
Key Takeaways