简体   繁体   中英

Sum values from nested dictionary - Python

Say I have the following dictionary

counts = 
 {(0, 0): {'00': 0, '01': 4908, '10': 0, '11': 5092},
 (0, 1): {'00': 0, '01': 5023, '10': 0, '11': 4977},
 (1, 0): {'00': 0, '01': 5058, '10': 0, '11': 4942},
 (1, 1): {'00': 0, '01': 4965, '10': 0, '11': 5035}}

and I want to sum counts[0,0] and counts [0, 1]to get

idealcounts = {'00': 0, '01': 9931, '10': 0, '11': 10069}

How do I extract the counts[0,r] values and then sum them all up? Thank you for your help.

You can just use collections.Counter and update it with the sub-dictionaries you want:

from collections import Counter

data = {
    (0, 0): {'00': 0, '01': 4908, '10': 0, '11': 5092},
    (0, 1): {'00': 0, '01': 5023, '10': 0, '11': 4977},
    (1, 0): {'00': 0, '01': 5058, '10': 0, '11': 4942},
    (1, 1): {'00': 0, '01': 4965, '10': 0, '11': 5035}
}

counts = Counter()

for k in ((0, 0), (0, 1)):
    counts.update(Counter(data[k]))

print(counts)
# Counter({'00': 0, '01': 9931, '10': 0, '11': 10069})

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