Python Practice › List Programs › Program 87
Bill per fruit purchased
Write a Python program to calculate the bill for each fruit purchased, from a price list and a quantity list.
Input
prices [["apple", 30], ["mango", 50], ["banana", 20], ["lichi", 50]]; bought [["apple", 2], ["mango", 10]]
Output
Fruit: Apple Bill: 60 Fruit: Mango Bill: 500 Total: 560
Approach
- Turn the price list into a dict for lookup, then multiply price by quantity.
Solution
prices = dict([["apple", 30], ["mango", 50], ["banana", 20], ["lichi", 50]])bought = [["apple", 2], ["mango", 10]]total = 0for fruit, qty in bought: bill = prices[fruit] * qty total += bill print(f"Fruit: {fruit.capitalize():8} Bill: {bill}")print("Total:", total)Output
Fruit: Apple Bill: 60 Fruit: Mango Bill: 500 Total: 560
Line by line
Line 1
dict() accepts a list of [key, value] pairs.
Learn the concept
New to this topic? Read the lesson, then come back.