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

前端 未结 17 2337
梦毁少年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:52

    The one with no extra imports!

    Their is a pythonic standard called EAFP(Easier to Ask for Forgiveness than Permission). Below code is based on that python standard.

    # The A and B dictionaries
    A = {'a': 1, 'b': 2, 'c': 3}
    B = {'b': 3, 'c': 4, 'd': 5}
    
    # The final dictionary. Will contain the final outputs.
    newdict = {}
    
    # Make sure every key of A and B get into the final dictionary 'newdict'.
    newdict.update(A)
    newdict.update(B)
    
    # Iterate through each key of A.
    for i in A.keys():
    
        # If same key exist on B, its values from A and B will add together and
        # get included in the final dictionary 'newdict'.
        try:
            addition = A[i] + B[i]
            newdict[i] = addition
    
        # If current key does not exist in dictionary B, it will give a KeyError,
        # catch it and continue looping.
        except KeyError:
            continue
    

    EDIT: thanks to jerzyk for his improvement suggestions.

提交回复
热议问题