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

How can I get the max value from specific key in nested dictionary

I have this dictionary and I want to get the max value of the ratio key only

I did this:

company_dict = {0: {'link': 'www.facebook.com', 'ratio': 0.91, 'size': 3},
                1: {'link': 'www.google.com', 'ratio': 0.92, 'size': 4}}
max_value = 0
for key, value in company_dict.items():
    for k, v in value.items():
        if k == 'ratio':
            if v > max_value:
                max_value = v

print(max_value)

Output:
0.92

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

Is there a better way ?

>Solution :

This also gives you the entire dictionary in addition to the max ratio:

best_company = max(company_dict.values(), key=lambda d: d["ratio"])
best_ratio = best_company["ratio"]
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