简体   繁体   English

如何在python中对字典中的特定值求和

[英]How to sum specific values within dictionary in python

I have the following nested dictionary and need to figure out how to sum all 'qty'. 我有以下嵌套的字典,需要弄清楚如何对所有“数量”求和。

data1 = {
    'Batch1': {
        'Pink': {'qty': 25, 'ordered': 15},
        'Blue': {'qty': 18, 'ordered': 20}
    },
    'Batch2': {
        'Coke': {'qty': 50, 'ordered': 100},
        'Sprite': {'qty': 30, 'ordered': 25}
    }
}

So the outcomes would be 123. 因此结果将是123。

You can use sum : 您可以使用sum

data1 = {'Batch1': {'Pink': {'qty': 25, 'ordered':15}, 'Blue': {'qty':18, 'ordered':20}}, 'Batch2': {'Coke': {'qty': 50, 'ordered': 100},'Sprite': {'qty':30, 'ordered':25}}}
result = sum(b['qty'] for c in data1.values() for b in c.values())

Output: 输出:

123

Your data1 was formatted funny, so here's what I used: 您的data1格式很有趣,所以这是我使用的格式:

{'Batch1': {'Blue': {'ordered': 20, 'qty': 18},
  'Pink': {'ordered': 15, 'qty': 25}},
 'Batch2': {'Coke': {'ordered': 100, 'qty': 50},
  'Sprite': {'ordered': 25, 'qty': 30}}}

If you're not sure how deeply nested your dict will be, you can write a function to recursively traverse the nested dict looking for the qty key and sum the values: 如果不确定dict嵌套的深度,可以编写一个函数来递归地遍历嵌套的dict以查找qty键并求和:

def find_key_vals(query_key, base_dict):
    values = []
    for k, v in base_dict.items():
        if k == query_key:
            values.append(v)
        elif isinstance(v, dict):
            values += find_key_vals(query_key, v)
    return values

find_key_vals('qty', data1)
# => [50, 30, 25, 18]

sum(find_key_vals('qty', data1))
# => 123

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

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