[英]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我想求和 counts[0,0] 和 counts [0, 1] 以获得
idealcounts = {'00': 0, '01': 9931, '10': 0, '11': 10069}
How do I extract the counts[0,r] values and then sum them all up?如何提取 counts[0,r] 值,然后将它们相加? Thank you for your help.
感谢您的帮助。
You can just use collections.Counter and update it with the sub-dictionaries you want:您可以只使用collections.Counter并使用您想要的子字典更新它:
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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.