Warm tip: This article is reproduced from stackoverflow.com, please click
dictionary list loops python

How to loop through lists and dictionaries

发布于 2020-03-27 15:46:59

I have a task where I have to loop through a list and then dictionaries to display the total stock worth of a cafe. I created some code that was reviewed but was told these comments:

Try looping through the menu list.

Each item can be used as keys in the dictionaries, to retrieve matching stock and price values.

Stock worth is the sum of each stock item multiplied by its price.

Im just having some trouble on how I would convert the list items to keys and then add them to the dictionary.

My original code was as follows:

menu = ['cheeseburger', 'chicken nuggets', 'fish', 'chips']
total = 0
stock = {1: 25,
         2: 20,
         3: 18,
         4: 10
         }

price = {1: 40,
         2: 35,
         3: 28,
         4: 18
         }

for stock in price:
    total = total + price[stock]
total = float(total)
print("The total stock worth is R" + (str(total)))

Thank you for any help and advice!

Questioner
user12739323
Viewed
75
scleronomic 2020-01-31 17:26

Try this:

menu = ['cheeseburger', 'chicken nuggets', 'fish', 'chips']
stock = {'cheeseburger': 25,
         'chicken nuggets': 20,
         'fish': 18,
         'chips': 10
         }

price = {'cheeseburger': 40,
         'chicken nuggets': 35,
         'fish': 28,
         'chips': 18
         }


total = 0
for food in menu:
    total += stock[food] * price[food]

print(total)