简体   繁体   English

我需要在嵌套字典中一起添加相同的键

[英]I need to add identical keys together in a nested dictionary

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.我需要一张通配符,将所有称为 fat 的键相加。

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

Something like that.像那样的东西。

(By the way the really long number is a barcode) (顺便说一句,真正长的数字是条形码)

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

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.您需要做的就是遍历您的字典并对其中每个项目中可能存在的每个子类别的值求和。

import pandas as pd

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},
}

df = pd.DataFrame(bcode_lib).T
df.loc['Total'] = df.drop("Item", axis=1).sum(numeric_only=None)
df

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM