简体   繁体   中英

Sum values of a Nested Dictionary with same key PYTHON

I have searched in the forum but havent found an option for my case.

I have this nested Dict

nestedDict = {5: {'B02682': 227808, 'B02598': 183263, 'B02617': 108001, 'B02512': 35536, 'B02764': 9908}, 4: {'B02598': 260549, 'B02682': 222883, 'B02617': 122734, 'B02512': 36765, 'B02764': 9504}, 1: {'B02598': 242975, 'B02682': 194926, 'B02617': 184460, 'B02512': 32509, 'B02764': 8974}, 0: {'B02617': 355803, 'B02598': 220129, 'B02682': 173280, 'B02764': 48591, 'B02512': 31472}, 2: {'B02617': 310160, 'B02598': 245597, 'B02682': 196754, 'B02512': 35021, 'B02764': 8589}, 3: {'B02617': 377695, 'B02598': 240600, 'B02682': 197138, 'B02764': 178333, 'B02512': 34370}}

And I need to sum the values of the elements with same key so I can get something like this

result = {'B02617': 1458853, 'B02598': 1393113, 'B02682': 1212789, 'B02764': 263899, 'B02512': 205673}

Thanks in advance

Try this:

result={}

for i in nestedDict:
    for k in nestedDict[i]:
        if k in result:
            result[k]+=nestedDict[i][k]
        else:
            result[k]=nestedDict[i][k]

>>> print(result)

{'B02682': 1212789, 'B02598': 1393113, 'B02617': 1458853, 'B02512': 205673, 'B02764': 263899}

Take a look at defaultdict .

from collections import defaultdict

result = defaultdict(int) # equivalent to defaultdict(lambda: 0)
for d in nestedDict.values():
    for key, value in d.items():
        result[key] += value

# if result must be of type dict uncomment the following line
# result = dict(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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