4

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?

  • Does this help? https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – Rukon Apr 13 '23 at 04:26
  • @Rukon although that does allow OP to get an answer, I feel the answer to their specific question about keys is even simpler, as shown below. – Grismar Apr 13 '23 at 04:29

2 Answers2

5

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.

Grismar
  • 27,561
  • 4
  • 31
  • 54
  • very crisp answer. I learnt one new thing today. Thanks @Grismar – rajkumar_data Apr 13 '23 at 04:35
  • 1
    Note that `sorted`, whose time complexity is *O(n log n)*, is not nearly as efficient as `heapq.nsmallest`, where the time complexity is *O(n log t)*, where *t* is the number of smallest values needed. – blhsing Apr 13 '23 at 04:47
  • @blhsing that seems to depend on what `n` is according to the [heapq documentation](https://docs.python.org/3/library/heapq.html#heapq.nsmallest) which states `The latter two functions perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function.` – Shorn Apr 13 '23 at 05:42
1

It can be solved as below:

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

# a list to store keys
min_keys = []

# how many minimum keys you need
count = 2

# iterate over dict items, sorted based on values 
for key,val in sorted(scores.items(), key=lambda x:x[1])[:count]:
    min_keys.append(key)
    
print(min_keys)
# prints [1,5]
rajkumar_data
  • 386
  • 2
  • 7
  • This is just a rewrite of the answer linked to by user @rukon. If you believe this is the answer to this question, you should not post it here, since that would make this question a duplicate. – Grismar Apr 13 '23 at 04:33