Markus
Markus

Reputation: 33

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 :

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.

Upvotes: 3

Views: 493

Answers (2)

Rakesh
Rakesh

Reputation: 82755

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

Upvotes: 7

Jacek Rojek
Jacek Rojek

Reputation: 1122

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)

Upvotes: 0

Related Questions