简体   繁体   English

嵌套字典的值总和

[英]Sum of values of nested dictionary

I have a sum of all values of nested dictionary with variable number of elements: For example:-我有元素数量可变的嵌套字典的所有值的总和:例如:-

a = {'val1': 3, 'val2': 4, 'val3': {'val4': 2, 'val5': 1}, 'val6': {'val7': 9, 'val8': {'val6': 43}}}

Let say I have a dictionary like above.假设我有一本像上面这样的字典。 And the output I want for this is:我想要的 output 是:

3+4+2+1+9+43 = 62

I have tried this but I know it will not work:我已经尝试过了,但我知道它不起作用:

dict_sum = 0
for k, v in a.items():

    if isinstance(v,dict):
        dict_sum += sum(v.values())
    else:
        dict_sum += v

But it will not work work for dictionary with multiple nested dictionaries.但它不适用于具有多个嵌套字典的字典。 Any help would be appreciated.任何帮助,将不胜感激。

One approach is using recursion.一种方法是使用递归。

For example:例如:

data = {'val1': 3, 'val2': 4, 'val3': {'val4': 2, 'val5': 1}, 'val6': {'val7': 9, 'val8': {'val6': 43}}}

def get_sum(data):
    s = 0
    for _, v in data.items():
        if isinstance(v, dict):
            s += get_sum(v)
        else:
            s += v
    return s
print(get_sum(data))  # --> 62

Using list comprehension使用列表理解

a = {'val1': 3, 'val2': 4, 'val3': {'val4': 2, 'val5': 1}, 'val6': {'val7': 9, 'val8': {'val6': 43}}}

def DeepSum(data):
    return sum([x if isinstance(x, int) else DeepSum(x) for x in data.values() ]) 

DeepSum(a)

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

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