0

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:

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?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135

3 Answers3

1

You could do it like this:

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

for _, k in sorted([(v, k) for k, v in d.items()])[:3]:
    print(k)

Output:

1
0.1
0.3
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
1

You can combine dictionary items method with sorted function and then filter only values with list comprehension and extract the three first results with slicing:

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

min_numbers = [key for key, value in sorted(d.items(), key=lambda item: item[1])][:3]
Martin Tovmassian
  • 1,010
  • 1
  • 10
  • 19
1

Try this:

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

Output

[1, 0.1, 0.3]
the__hat_guy
  • 133
  • 8