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

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

    OK so this works by making a union set of all possible keys dict_a.keys() | dict_b.keys() and then using dict.get which by default returns None if the key is not present (rather than throwing an error). We then take the max (of the one which isn't None).

    def none_max(a, b):
        if a is None:
            return b
        if b is None:
            return a
        return max(a, b)
    
    def max_dict(dict_a, dict_b):
       all_keys = dict_a.keys() | dict_b.keys()
       return  {k: none_max(dict_a.get(k), dict_b.get(k)) for k in all_keys}
    

    Note that this will work with any comparable values -- many of the other answers fail for negatives or zeros.


    Example: Inputs:

    dict_a = {'a': 3, 'b': 2, 'c': 6}
    
    dict_b = {'b': 7, 'c': 4, 'd': 1}
    

    Outputs:

    max_dict(dict_a, dict_b)  # == {'b': 7, 'c': 6, 'd': 1, 'a': 3}
    

提交回复
热议问题