Sakeer
Sakeer

Reputation: 2006

Find sum of all values in dict of dict

I have dictionary like below,

 {
    'AAA': 
        {'NKA': 2, 'total': 4, 'Cleared': 2, 'NRM-TY': 3, 'KLAOO': 1, 'COREI': 1, 'MFTT': 2}, 
    'DDD': 
        {'Cleared': 2, 'total': 1, 'KLAOO': 1, 'COREI': 1, 'NRM-TY': 1}, 
    'NNN': 
        {'Cleared': 1, 'total': 1, 'KLAOO': 4,}, 
    'AANN': 
        {'Cleared': 1, 'total': 1, 'NRM-TY': 2}
}

I need to get sum of all the keys value like below,

{'NKA': 2, 'total': 7, 'Cleared': 6, 'NRM-TY': 6, 'KLAOO': 6, 'COREI': 2, 'MFTT': 2}

I can able to achieve this using below code,

result = {}
for k,v in a.items():
    for p,q in v.items():
        if p in result:
            result[p] += q
        else:
            result[p] = q

I just wanted to know is there any simple way to do the same...

Upvotes: 0

Views: 65

Answers (2)

Nakor
Nakor

Reputation: 1514

You can also consider using the pandas library:

import pandas as pd

pd.DataFrame(your_dict).sum(axis=1)

You get:

COREI      2.0
Cleared    6.0
KLAOO      6.0
MFTT       2.0
NKA        2.0
NRM-TY     6.0
total      7.0

Upvotes: 1

Rakesh
Rakesh

Reputation: 82785

Use collections.Counter

Ex:

from collections import Counter
data = {
    'AAA': 
        {'NKA': 2, 'total': 4, 'Cleared': 2, 'NRM-TY': 3, 'KLAOO': 1, 'COREI': 1, 'MFTT': 2}, 
    'DDD': 
        {'Cleared': 2, 'total': 1, 'KLAOO': 1, 'COREI': 1, 'NRM-TY': 1}, 
    'NNN': 
        {'Cleared': 1, 'total': 1, 'KLAOO': 4,}, 
    'AANN': 
        {'Cleared': 1, 'total': 1, 'NRM-TY': 2}
}

result = Counter()    
for _, v in data.items():
    result += Counter(v)
print(result)

Output:

Counter({'total': 7, 'NRM-TY': 6, 'Cleared': 6, 'KLAOO': 6, 'NKA': 2, 'COREI': 2, 'MFTT': 2})

Upvotes: 3

Related Questions