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

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

    Merging three dicts a,b,c in a single line without any other modules or libs

    If we have the three dicts

    a = {"a":9}
    b = {"b":7}
    c = {'b': 2, 'd': 90}
    

    Merge all with a single line and return a dict object using

    c = dict(a.items() + b.items() + c.items())
    

    Returning

    {'a': 9, 'b': 2, 'd': 90}
    

提交回复
热议问题