Computing shopping-list total using dictionaries

Ibraheem Kolawole picture Ibraheem Kolawole · Mar 22, 2015 · Viewed 10.6k times · Source

I tried calling the total of dictionary values for a shopping list made in list, but error has been coming up and summing to 10.5 instead of 7.5, it is supposed to give out the total price of items in a list, any list.

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!

def compute_bill(food):
    total = 0
    for item in food:
        item = shopping_list(prices[key])
        total += item
    return total
shopping_list = ["banana", "orange", "apple"]  

Answer

ssm picture ssm · Mar 22, 2015

You can use list comprehensions ...

sum([ prices[s] for s in shopping_list ])