温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to loop through lists and dictionaries
dictionary list loops python

python - 如何遍历列表和字典

发布于 2020-03-27 16:17:57

我有一个任务,我必须遍历列表,然后字典以显示咖啡馆的总存货价值。我创建了一些经过审查的代码,但被告知这些评论:

尝试遍历菜单列表。

每个项目都可以用作字典中的键,以检索匹配的库存和价格值。

库存价值是每个库存项目的总和乘以其价格。

我只是在如何将列表项转换为键,然后将其添加到字典中遇到麻烦。

我的原始代码如下:

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)))

感谢您的帮助和建议!

查看更多

查看更多

提问者
user12739323
被浏览
151
scleronomic 2020-01-31 17:26

尝试这个:

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)