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

Get the key corresponding to the 3 minimum values within a dictionary

I have a Python dictionary, and I want to find the keys for the 3 minimal values in it.

For example:

Input: d = {1 : 10 , 0.1 : 15 , 0.3 : 18 , 0.001 : 25 , 0.003 : 42}
Output: [1, 0.1 , 0.3]

I know how to grab only one minimum value with a list comprehension:

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

min_val = min(d.values())
min_numbers = [num for num, value in d.items() if value == min_val]

but how do I do it for three?

>Solution :

Try this:

l = [item for item in sorted(d, key=d.get)][0:3]
print(l)

Output

[1, 0.1, 0.3]
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