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

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

    What about

    {
        k:max(
            dict_a.get(k,-float('inf')),
            dict_b.get(k,-float('inf'))
        ) for k in dict_a.keys()|dict_b.keys()
    }
    

    which returns

    {'A': 3, 'D': 1, 'C': 6, 'B': 7}
    


    With

    >>> dict_a = {'A':3, 'B':2, 'C':6}
    >>> dict_b = {'B':7, 'C':4, 'D':1}
    

提交回复
热议问题