Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

前端 未结 17 2347
梦毁少年i
梦毁少年i 2020-11-22 01:50

For example I have two dicts:

Dict A: {\'a\': 1, \'b\': 2, \'c\': 3}
Dict B: {\'b\': 3, \'c\': 4, \'d\': 5}

I need a pythonic way of \'comb

17条回答
  •  无人及你
    2020-11-22 02:57

    The above solutions are great for the scenario where you have a small number of Counters. If you have a big list of them though, something like this is much nicer:

    from collections import Counter
    
    A = Counter({'a':1, 'b':2, 'c':3})
    B = Counter({'b':3, 'c':4, 'd':5}) 
    C = Counter({'a': 5, 'e':3})
    list_of_counts = [A, B, C]
    
    total = sum(list_of_counts, Counter())
    
    print(total)
    # Counter({'c': 7, 'a': 6, 'b': 5, 'd': 5, 'e': 3})
    

    The above solution is essentially summing the Counters by:

    total = Counter()
    for count in list_of_counts:
        total += count
    print(total)
    # Counter({'c': 7, 'a': 6, 'b': 5, 'd': 5, 'e': 3})
    

    This does the same thing but I think it always helps to see what it is effectively doing underneath.

提交回复
热议问题