I have two dictionaries which I need to multiply and get the total of, both with the same keys (I need the total of the stock and price of some items).
# Create a list "menu" with 4 items
menu = ["sandwich", "burger", "fish", "chips"]
# Create a dictionary "stock" with the stock value for each item in the menu
stock = {"sandwich" : 6, "burger" : 5, "fish" : 6, "chips" : 10}
# Create a dictionary "price" with the price for each item in the menu
price = {"sandwich" : 4.50, "burger" : 6.00, "fish" : 6.50, "chips" : 3.50}
# Get the values from stock and price for each menu item and multiply by eachother
for key in price:
menu_stock = price[key] * stock[key]
# Get the sum of these values
total_stock_worth = sum(menu_stock)
# Print statement with the calculated total stock worth
print("The total stock worth is £" + str("{:.2f}".format(total_stock_worth)))
I get the error message (for line 12: total_stock_worth = sum(menu_stock)): TypeError: 'float' object is not iterable
The output I'm after is: The total stock worth is £131.00
The sum
function work with iterable
ex: list, set
etc.. In your code menu_stock
is a float
not an iterable
.
To solved your problem declare menu_stock
as a list and append
the product of each of the stock
and price
to it. After the loop, call the sum
function to calculate the total_stock_worth
.
Also you don't need to call the str()
method format()
does that automatically for you.
Solution
# Create a list "menu" with 4 items
menu = ["sandwich", "burger", "fish", "chips"]
# Create a dictionary "stock" with the stock value for each item in the menu
stock = {"sandwich" : 6, "burger" : 5, "fish" : 6, "chips" : 10}
# Create a dictionary "price" with the price for each item in the menu
price = {"sandwich" : 4.50, "burger" : 6.00, "fish" : 6.50, "chips" : 3.50}
# declare menu_stock as list
menu_stock = []
# Get the values from stock and price for each menu item and multiply by eachother
for key in price:
menu_stock.append(price[key] * stock[key])
# Get the sum of these values
total_stock_worth = sum(menu_stock)
# Print statement with the calculated total stock worth
print("The total stock worth is £{:.2f}".format(total_stock_worth))