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

后端 未结 6 720
悲哀的现实
悲哀的现实 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条回答
  •  梦毁少年i
    2021-01-26 19:24

    Extending this so you can have any number of dictionaries in a list rather than just two:

    a = {'a': 3, 'b': 2, 'c': 6}
    b = {'b': 7, 'c': 4, 'd': 1}
    c = {'c': 1, 'd': 5, 'e': 7}
    
    all_dicts = [a,b,c]
    
    from functools import reduce
    
    all_keys = reduce((lambda x,y : x | y),[d.keys() for d in all_dicts])
    
    max_dict = { k : max(d.get(k,0) for d in all_dicts) for k in all_keys }
    

提交回复
热议问题