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

Python – Dicts: how to find out what the key(s) with the highest int as value is/are

In a dict, I want to find all keys that have the highest value, so in this example not only key ‘D’, but also key ‘B’. How do I do this (in the most efficient way)?

some_dict = {
'A': 2, 
'B': 18, 
'C': 7, 
'D': 18
}

highest_keys(some_dict)

# Result should be: ['B', 'D'] or {'B': 18, 'D': 18}, both options would work

max only gives the last key with the highest value, but I need all.
Thank you in advance! 🙂

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

>Solution :

You may find the highest value, and then retrieve the keys:

highval = max(somedict.values())
[k for k in somedict if somedict[k] == highval]
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