merging two python dicts and keeping the max key, val in the new updated dict

后端 未结 6 764
悲哀的现实
悲哀的现实 2021-01-26 18:30

I need a method where I can merge two dicts keeping the max value when one of the keys, value are in both dicts.

dict_a maps \"A\", \"B\", \"C\" to 3, 2, 6

dict_

6条回答
  •  一整个雨季
    2021-01-26 19:14

    Yet another solution:

    a = {"A":3, "B":2, "C":6}
    b = {"B":7, "C":4, "D":1}
    

    Two liner:

    b.update({k:max(a[k],b[k]) for k in a if b.get(k,'')})
    res = {**a, **b}
    

    Or if you don't want to change b:

    b_copy = dict(b)
    b_copy.update({k:max(a[k],b[k]) for k in a if b.get(k,'')})
    res = {**a, **b_copy}
    
    > {'A': 3, 'B': 7, 'C': 6, 'D': 1}
    

提交回复
热议问题