Home > Blockchain >  Calculate values in a dictionary
Calculate values in a dictionary

Time:09-26

I have following dictionary:

food_calories = {"Burger": 400, "Ice Cream": 350, "Cake": 640, "Chicken": 400, "Rice": 250, "Salad": 40, "Fanta": 170, "Coke": 200, "Beef": 350}

How can I calculate the sum of some values of the dictionary? E.g. Ice Cream", "Chicken", "Beef") #=> 1100

I only get errors and I'm stuck in setting up the function.

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

CodePudding user response:

Is this what you are looking for?

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

You can replace the food_calories.get(i,0) with food_calories[i] but if you pass an item that doesn't exist in the food_calories dictionary it will throw an error.

Instead, food_calories.get(i,0) returns 0 as default value if key is not found, therefore only returning sum for items that exist and doing some exception handling.

CodePudding user response:

You can access the value of each key by using this syntax: food_calories['item'], where item is some key in your dictionary.

This is a sample output where food_calories is the dict you defined in your post:

>>> food_calories['Rice']   food_calories['Burger']
650
  • Related