Home > Back-end >  I need to add identical keys together in a nested dictionary
I need to add identical keys together in a nested dictionary

Time:01-21

There's a list of food items that have subcategories of protein, calories, sugars, etc. I would like to add the the keys of all the food items to have the 'total protein for today' and 'total calories for today' and so on.

bcode_lib = {
6294001819226: {"Item": "Snickers", "Fat":  6.2, "Energy":  519, "Sugars":  12.4, "Energy-kcal":    124, "Protein": 7, "Carbohydrates": 12.4, "Saturated-fat":  2.5},

5000159366243: {"Item": "Twix", "Fat":  23.7, "Energy": 2071, "Sugars": 48.8, "Energy-kcal":    495, "Protein": 4.5, "Carbohydrates":   64.6, "Saturated-fat":  13.7},
}

I can't do this:

print("Total fat is:", (bcode_lib[6294001819226]['Fat']   bcode_lib[5000159366243]['Fat']))

Although it works this list actively changes its contents, so typing out the key name itself would never work. I would need a wild card that adds up all the keys called fat.

print("Total fat is:", bcode_lib[*]['Fat']))

Something like that.

(By the way the really long number is a barcode)

CodePudding user response:

Do you try loop?

total_fat = sum(item['Fat'] for item in bcode_lib.values())
total_calories = sum(item['Energy-kcal'] for item in bcode_lib.values())
total_protein = sum(item['Protein'] for item in bcode_lib.values())

print(f"Total fat is: {total_fat}")
print(f"Total calories: {total_calories}")
print(f"Total protein: {total_protein}")

Total fat is: 29.9
Total calories: 619
Total protein: 11.5

CodePudding user response:

You can achieve what you want with:

bcode_lib = {
6294001819226: {"Item": "Snickers", "Fat":  6.2, "Energy":  519, "Sugars":  12.4, "Energy-kcal":    124, "Protein": 7, "Carbohydrates": 12.4, "Saturated-fat":  2.5},

5000159366243: {"Item": "Twix", "Fat":  23.7, "Energy": 2071, "Sugars": 48.8, "Energy-kcal":    495, "Protein": 4.5, "Carbohydrates":   64.6, "Saturated-fat":  13.7},
}

subcategories = {}
for b_code, item in bcode_lib.items():
    for sub_c, val in item.items():
        if sub_c == 'Item':
            continue
        
        if sub_c not in subcategories:
            subcategories[sub_c] = val
        else:
            subcategories[sub_c]  = val

All you need to do is iterate through your dictionary and sum the values of each subcategory that may exist in each item of it.

  • Related