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

Extracting the Minimum x Value Keys from Dictionary

Suppose we wish to extract the minimum value from a dictionary like so

scores = {
    0:1.3399288498085087,
    1:1.2672683347433629,
    3:1.6999159970296505, 
    4:1.8410942584597279,
    5:1.336658057628646
}

#find minimum value in dictionary
minimum_value = min(scores.values())

#get keys with minimal value using list comprehension
minimum_keys = [key for key in scores if scores[key]==minimum_value]

minimum_keys

This returns the key with the lowest value. However, what if I wish to extract the minimum 2 keys and put them into a list? What if I wanted the minimum 20? How would I go about doing this for an arbitrary number of minimal values desired?

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 :

In fact, the problem is simpler than you think:

scores = {
    0:1.3399288498085087,
    1:1.2672683347433629,
    3:1.6999159970296505, 
    4:1.8410942584597279,
    5:1.336658057628646
}

# minimum key
print(min(scores, key=scores.get))

# n minimum keys
print(sorted(scores, key=scores.get)[:3])

Output:

1
[1, 5, 0]

Both min and sorted allow you to provide a key which is some function to be called with a value, to compute an associated value to be used for sorting. By providing scores.get as that function, you can sort keys by their matching value, which is what you want.

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