Add values from two dictionaries

前端 未结 5 931
萌比男神i
萌比男神i 2021-01-02 08:07
dict1 = {a: 5, b: 7}
dict2 = {a: 3, c: 1}

result {a:8, b:7, c:1}

How can I get the result?

5条回答
  •  灰色年华
    2021-01-02 08:24

    this is a one-liner that would do just that:

    dict1 = {'a': 5, 'b': 7}
    dict2 = {'a': 3, 'c': 1}
    
    result = {key: dict1.get(key, 0) + dict2.get(key, 0)
              for key in set(dict1) | set(dict2)}
    # {'c': 1, 'b': 7, 'a': 8}
    

    note that set(dict1) | set(dict2) is the set of the keys of both your dictionaries. and dict1.get(key, 0) returns dict1[key] if the key exists, 0 otherwise.

提交回复
热议问题