Compare a dictionary with list of dictionaries and return index from the list which has higher value than the separate dictionary

Question:

I have a list of dictionaries and a separate dictionary having the same keys and only the values are different. For example the list of dictionaries look like this:

[{'A': 0.102, 'B': 0.568, 'C': 0.33}, {'A': 0.026, 'B': 0.590, 'C': 0.382}, {'A': 0.005, 'B': 0.857, 'C': 0.137}, {'A': 0.0, 'B': 0.962, 'C': 0.036}, {'A': 0.0, 'B': 0.991, 'C': 0.008}] 

and the separate dictionary looks like this:

{'A': 0.005, 'B': 0.956, 'C': 0.038}

I want to compare the separate dictionary with the list of dictionaries and return the index from the list which has higher value than the separate dictionary. In this example, the indices would be 3, 4 as the dictionary in indices 3 and 4 has a higher value for key 'B' since 'B' has the highest value in the separate dictionary.

Any ideas on how I should I proceed the problem?

Asked By: Pritam Deka

||

Answers:

are you sure that it should be only index 4?

dict_list = [{'A': 0.102, 'B': 0.568, 'C': 0.33}, 
             {'A': 0.026, 'B': 0.590, 'C': 0.382}, 
             {'A': 0.005, 'B': 0.857, 'C': 0.137}, 
             {'A': 0.0, 'B': 0.962, 'C': 0.036}, 
             {'A': 0.0, 'B': 0.991, 'C': 0.008}] 

d = {'A': 0.005, 'B': 0.956, 'C': 0.038}

max_val = max(d.values())
idxmax = [i for i,j in enumerate(dict_list) if max(j.values()) > max_val]

print(idxmax)  # [3, 4]
Answered By: SergFSM

You can use enumerate for finding index of max value:

org = [
    {'A': 0.102, 'B': 0.568, 'C': 0.33}, 
    {'A': 0.026, 'B': 0.590, 'C': 0.382}, 
    {'A': 0.005, 'B': 0.857, 'C': 0.137}, 
    {'A': 0.0, 'B': 0.962, 'C': 0.036}, 
    {'A': 0.0, 'B': 0.991, 'C': 0.008}
] 

com = {'A': 0.005, 'B': 0.956, 'C': 0.038}

def fnd_index(org, com):
    key_max, val_max = max(com.items(), key=lambda x: x[1])
    print('key_max:', key_max)
    print('val_max:', val_max)
    res = []
    for idx, dct in enumerate(org):
        if dct[key_max] > val_max:
            res.append(idx)
    return res


fnd_index(org, com)
# [3, 4]
Answered By: I'mahdi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.