python中两个嵌套字典中相似键的和值

2024-05-05 01:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的嵌套字典:

data = {
    "2010":{
            'A':2,
            'B':3,
            'C':5,
            'D':-18,
        },
    "2011":{
            'A':1,
            'B':2,
            'C':3,
            'D':1,
        },
    "2012":{
            'A':1,
            'B':2,
            'C':4,
            'D':2
        }
    }

在我的例子中,从2010年到2012年,我需要根据其相似的键来计算所有值。。 所以我预期的结果应该是这样的:

^{pr2}$

Tags: data字典例子pr2
2条回答

您可以使用collections.Counter()(仅适用于正值!)公司名称:

In [17]: from collections import Counter
In [18]: sum((Counter(d) for d in data.values()), Counter())
Out[18]: Counter({'C': 12, 'B': 7, 'A': 4, 'D': 3})

请注意,根据python文档,Counter仅为正值的用例设计:

The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison. The elements() method requires integer counts. It ignores zero and negative counts.

所以,如果你想得到一个综合的结果,你可以手工求和。collections.defaultdict()是解决此问题的好方法:

^{pr2}$

试试这个

reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), data.values())

结果

^{pr2}$

相关问题 更多 >