Python Dictionary comprehension
Construct a revised price table by calculating each value from its previous price.
A simple example
Dictionary comprehension
- Start with A = 1, B = 2
- Do this Add 1 to each value
- Result A = 2, B = 3
Syntax
{key: price + 1 for key, price in prices.items()}
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyAdd a packing charge to each listed price
A café starts packing takeaway orders in reusable boxes. The manager adds one unit to each listed price and checks the new soup price before publishing the board.
From the programprices = {"Soup": 4, "Salad": 6}
Result5
prices = {"Soup": 4, "Salad": 6}
revised = {item: price + 1 for item, price in prices.items()}
print(revised["Soup"])
5
The soup mapping in the revised table includes one unit for packing.
Advertisements
Reprint stationery prices
A school shop increases every price by two credits. Every price gets the same increase. Find the revised value for the first item.
GivenPen 7 · increase 2
Worked result9
Revise rental rates
A studio adds a three-credit cleaning fee to every rental. Every price gets the same increase. Find the revised value for the first item.
GivenStand 12 · increase 3
Worked result15
What to watch for
Save the result as the new price table if it should become the active menu.