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

后端 未结 6 767
悲哀的现实
悲哀的现实 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:15

    If you know that all your values are non-negative (or have a clear smallest number), then this oneliner can solve your issue:

    a = dict(a=3,b=2,c=6)
    b = dict(b=7,c=4,d=1)
    merged = { k: max(a.get(k, 0), b.get(k, 0)) for k in set(a) | set(b) }
    

    Use your smallest-possible-number instead of the 0. (E. g. float('-inf') or similar.)

提交回复
热议问题