I'm working with the below dictionaries and list:
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3}
groceries = [‘apple’, ‘banana’, ‘pear’]
I need to write code to sum the total number in stock of the items in the groceries list. The second part is to write code to print the total value in stock of all items. The program can iterate over the stock dictionary and for each item multiply the number in stock times the price of that item in the prices dictionary. I have tried a few different ways. I have this, but it doesn't work. groceries = ['apple', 'banana', 'pear']
def sum_list(groceries):
sum_numbers = 0
for x in groceries:
sum_numbers += x
return sum_numbers
def sum_list(groceries, stock, prices): sum_numbers = 0 for x in groceries: if x in stock: sum_numbers += stock[x] * prices[x] return sum_numbers # Testing the function here. ignore/remove the code below if not required stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15} prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3} groceries = ['apple', 'banana', 'pear'] print(sum_list(groceries, stock, prices))
Get Answers For Free
Most questions answered within 1 hours.