简体   繁体   English

嵌套默认字典计数值

[英]nested default dictionary counting values

I've got a defaultdict with a nested dictionary from which I'm trying to get the sum of the values. 我有一个带有嵌套词典的defaultdict,我试图从中获取值的总和。 But I've been struggling to find a way to do this. 但是我一直在努力寻找一种方法来做到这一点。

In the example below, I'm trying to count all the count values: 在下面的示例中,我尝试对所有count数值进行count

from collections import defaultdict

x = defaultdict(dict)

x['test1']['count'] = 14
x['test4']['count'] = 14
x['test2']['count'] = 14
x['test3']['count'] = 14

print x

""" methods I've tried """

# print x.values()
# print sum(x for y in x.values() for x in y['count'].iteritems())
# print sum(x.itervalues())

The methods above that I've tried (in many different variations) didn't provide the desired results. 我尝试过的上述方法(有许多不同的变体)没有提供理想的结果。

Any clues or assistance as to where I may be in error? 关于我可能出错的任何线索或帮助?

只需求sum(x[k]['count'] for k in x)

If you have to caluculate sum of just 'count' key, you may do: 如果您只需要计算'count'键的总和,则可以执行以下操作:

>>> sum(y['count'] for y in x.values())
56

If there is a possibility of having other keys as well (apart from 'count'), and you want to calculate sum of all the values, then you have to do: 如果还有其他键(除了“ count”之外)的可能性,并且您要计算所有值的总和,则必须执行以下操作:

>>> sum(z for y in x.values() for z in y.values())
56

# OR,
# import itertools
# sum(itertools.chain(*[y.values() for y in x.values()]))

If you want to sum the values of all sub dictionaries, sum twice: 如果要对所有子字典的值求和,请求和两次:

>>> sum(sum(y.values()) for y in x.values())
56

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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