Python Merge 2 or more Dicts using a value to handle duplicate keys
Question: I am merging dictionaries that have some duplicate keys. The values will be
different and I want to ignore the lower value record.

    
    
    dict1 = {1 :["in",1], 2 :["out",1], 3 :["in",1]}
    dict2 = {1 :["out",2], 2 :["out",1]}
    

If the keys are equal I want the `key[0][1`] with the greatest value to be in
the new dict. The output of merging these 2 dicts should be:

    
    
    dict3 = {1 :["out",2], 2 :["out",1], 3 :["in",1]}
    

The only way I know to solve this is to run a loop with a condition to
determine which one to add into the merged dict. Is there a more pythonic way
of doing it?

The duplicate keys will be very few and far between, less than 1% if that will
make any difference to the end solution.


Answer: A single dictionary comprehension can do this

    
    
    from operator import itemgetter
    {k: max(dict1.get(k, (None, float('-Inf'))), dict2.get(k, (None,float('-Inf'))),
    key=itemgetter(1)) for k in dict1.viewkeys() | dict2.viewkeys()}
    

