Add values from two dictionaries

前端 未结 5 918
萌比男神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:23

    A quick dictionary comprehension that should work on any classes which accept the + operator. Performance might not be optimal.

    {
        **dict1,
        **{ k:(dict1[k]+v if k in dict1 else v)
            for k,v in dict2.items() }
    }
    

提交回复
热议问题