Python通过将值相加将字典词典合并为一个词典 [英] Python merging dictionary of dictionaries into one dictionary by summing the value

查看:62
本文介绍了Python通过将值相加将字典词典合并为一个词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字典中的所有字典合并,而忽略主要字典键,并按值求和其他字典的值.

I want to merge all the dictionaries in a dictionary, while ignoring the main dictionary keys, and summing the value of the other dictionaries by value.

输入:

{'first':{'a': 5}, 'second':{'a': 10}, 'third':{'b': 5, 'c': 1}}

输出:

{'a': 15, 'b': 5, 'c': 1}

我做到了:

def merge_dicts(large_dictionary):
    result = {}
    for name, dictionary in large_dictionary.items():
        for key, value in dictionary.items():
            if key not in result:
                result[key] = value
            else:
                result[key] += value
    return result

哪种方法有用,但我认为这不是一个好方法(或更少的"pythonic").

Which works, but I don't think it's such a good way (or less "pythonic").

顺便说一句,我不喜欢我写的标题.如果有人认为措词更好,请编辑.

By the way, I don't like the title I wrote. If anybody thinks of a better wording please edit.

推荐答案

您可以对作为dict子类的计数器求和:

You can sum counters, which are a dict subclass:

>>> from collections import Counter
>>> sum(map(Counter, d.values()), Counter())
Counter({'a': 15, 'b': 5, 'c': 1})

这篇关于Python通过将值相加将字典词典合并为一个词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆