我有一个嵌套字典:
{'apple': {'a': 1, 'b': 4, 'c': 2},
'orange': {'a': 4, 'c': 5},
'pear': {'a': 1, 'b': 2}}
我想要做的是摆脱外键并对内部键的值求和,以便我有一个新的字典,如下所示:
{'a': 6, 'b': 6, 'c': 7}
答案 0 :(得分:7)
您可以使用Counter类:
>>> from collections import Counter
>>> d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
>>> sum(map(Counter, d.values()), Counter())
Counter({'c': 7, 'a': 6, 'b': 6})
答案 1 :(得分:3)
from collections import defaultdict
d = defaultdict(int)
for dct in yourdict.values():
for k,v in dct.items():
d[k] += v
这个答案的主要优点是它可以回溯到python2.5。对于python2.7 +,请参阅@DSM和@BigYellowCactus发布的解决方案。
答案 2 :(得分:3)
这是另一个collections.Counter
解决方案,它不像其他人一样,但我认为它更清洁:
from collections import Counter
d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
counts = Counter()
for v in d.values():
counts.update(v)
答案 3 :(得分:2)
Counter对象旨在使这样的事情变得非常简单:
>>> from collections import Counter
>>> d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
>>> sum((Counter(v) for v in d.itervalues()), Counter())
Counter({'c': 7, 'a': 6, 'b': 6})