我有以下字典:
food_calories = {"Burger": 400, "Ice Cream": 350, "Cake": 640, "Chicken": 400, "Rice": 250, "Salad": 40, "Fanta": 170, "Coke": 200, "Beef": 350}
如何计算字典中某些值的和?例如:冰淇淋、鸡肉、牛肉#=>1100
我只得到错误,我被困在设置函数。
min_calories = min(zip(food_calories.values(), food_calories.keys()))
max_calories = max(zip(food_calories.values(), food_calories.keys()))
print("min_calories:",min_calories)
print("max_calories:",max_calories)
values = food_calories.values()
total = sum(values)
print(total)
def food_calories_sum():
for k in food_calories:
return k
这是你要找的吗?
l = ["Ice Cream", "Chicken", "Beef"]
def food_calories_sum(l):
return sum([food_calories.get(i,0) for i in l])
food_calories_sum(l)
1100
您可以将food_calories.get(i,0)
替换为food_calories[i]
,但如果传递的项不存在于food_calories
字典中,则会抛出错误。
相反,如果没有找到key,food_calories.get(i,0)
返回0作为默认值,因此只返回存在项的sum并做一些异常处理。
您可以使用以下语法访问每个键的值:food_calories['item']
,其中item
是字典中的某个键。
这是一个示例输出,其中food_calories
是您在帖子中定义的字典:
>>> food_calories['Rice'] + food_calories['Burger']
650