Search code examples
pythonlistloopsdictionarycomparison

How to keep only the key-value-pair with the global max value over several dictionaries?


Input:

A= [{'A':0.4, 'B':0.8, 'C':1.0},
    {'A':0.5, 'B':0.9, 'C':0.0}]

Desired Output:

A=[{'C':1.0},{'A':0.5, 'B':0.9}]

Note: I wanna iterate through and keep only the key with the maximum value among same keys !! And list of dictionaries should be kept !


Solution

  • A more concise approach based on @Ioannis' answer

    max_dict = {k: max([d[k] for d in A]) for k in A[0]}
    result = [{k: v for k, v in i.items() if v == max_dict[k]} for i in A]
    print(result)
    

    output:

    [{'C': 1.0}, {'A': 0.5, 'B': 0.9}]
    

    Detailed approach:

    You can create a dictionary with max values and check with it for each list item. You can implement it using 2 for loops.

    A = [{'A': 0.4, 'B': 0.8, 'C': 1.0},
         {'A': 0.5, 'B': 0.9, 'C': 0.0}]
    
    max_dict = {}
    
    for a_dict in A:
        for key, value in a_dict.items():
            if key not in max_dict or max_dict[key] < value:
                max_dict[key] = value
    
    result = []
    for a_dict in A:
        temp_dict = {}
        for key, value in a_dict.items():
            if value == max_dict[key]:
                temp_dict[key] = value
        result.append(temp_dict)
    
    print(result)
    

    output:

    [{'C': 1.0}, {'A': 0.5, 'B': 0.9}]