添加或合并python词典而不会丢失

时间:2010-10-05 14:16:41

标签: python dictionary merge count add

我正在尝试计算在两台服务器上的日志文件中找到的IP地址,然后将字典统计数据合并在一起,而不会丢失元素或计数。我在另一个堆栈溢出问题中找到了部分解决方案但是你可以看到它丢弃了'10.10.0.1':7对。

>>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
>>> b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
>>> c = {}
>>> for elem in a:
...     c[elem] = b.get(elem, 0) + a[elem]
...
>>> print c
{'55.55.55.55': 10, '12.12.12.12': 5, '127.0.0.1': 6, '192.168.1.21': 50}

计数正在加在一起,但如果密钥在dict中不存在,则会被删除。我无法弄清楚逻辑的最后一点......也许是另一个对于b中的elem:如果a.get(elem,0)存在:pass else将它添加到c?

6 个答案:

答案 0 :(得分:5)

如果你有Python 2.7+,请尝试collections.Counter

否则请尝试以下操作:

a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
c = {}
for dictionary in (a,b):
    for k,v in dictionary.iteritems():
        c[k] = c.get(k, 0) + v

答案 1 :(得分:5)

>>> from collections import Counter
>>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
>>> b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
>>> Counter(a) + Counter(b)
Counter({'192.168.1.21': 50, '55.55.55.55': 10, '10.10.0.1': 7, '127.0.0.1': 6, '12.12.12.12': 5})

答案 2 :(得分:5)

在您的代码中,将c = {}替换为c = b.copy()

答案 3 :(得分:2)

怎么样:

c = dict((k, a.get(k, 0) + b.get(k, 0)) for k in set(a.keys() + b.keys()))

答案 4 :(得分:1)

如果我得到它,这对你的问题应该是一个非常通用的答案。

def merge_sum_dictionaries(*dicts):
    result_dict = {}
    for d in dicts:
        for key, value in d.iteritems():
            result_dict.setdefault(key, 0)
            result_dict[key] += value
    return result_dict



if __name__ == "__main__":
    a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
    b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}

    print merge_sum_dictionaries(a, b)

输出:

{'55.55.55.55': 10, '10.10.0.1': 7, '12.12.12.12': 5, '127.0.0.1': 6, '192.168.1.21': 50}

答案 5 :(得分:1)

python 2.6及更高版本的解决方案:

from collections import defaultdict

def merge_count_dicts(*dicts):
    result = defaultdict(int)
    for d in dicts:
        for k, v in d.items():
            result[k] += v
    return result

def test():
    a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
    b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
    c = merge_count_dicts(a, b)
    print c

if __name__ == '__main_':
    test()