Add or merge lossless python dictionaries

I am trying to count the ip addresses found in the log file on two servers and then combine the dictionary statistics together without losing any items or counts. I found a partial solution in another question, but as you can see, it falls by a couple '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}

The accounts come together, but if the key does not exist in dict a, it is discarded. I'm having trouble figuring out the last bit of logic ... maybe one more for an element in b: if a.get (elem, 0) exists: pass else, add it to c?

+3
source share
6 answers

In your code, replace c = {}withc = b.copy()

+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
+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})
+5

:

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

This should be a fairly general answer to your question if I got it.

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)

Conclusion:

{'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}
+1
source

Solution for python 2.6 and higher:

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()
+1
source

Source: https://habr.com/ru/post/1768067/


All Articles