Overview
Turn a list of pairs into a dictionary in one readable line, keeping only the entries you want.
- {key: value for ...}
- Unpacking pairs in the loop
- Filtering with if
Short Course
A dict comprehension builds a dictionary from a loop: key: value
first, then the loop, then an optional if.
stock = [("apple", 4), ("pear", 0)]
counts = {name: n for name, n in stock}
# {'apple': 4, 'pear': 0}
in_stock = {name: n for name, n in stock if n > 0}
# {'apple': 4}
Task
Write price_index(items) that turns (name, price) pairs into a dict with
lowercase names as keys, skipping items whose price is 0.
Test Suites
Pending
Stdout