Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any ideas on how I should I proceed the problem?

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading