Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum non zero value in dictionary (Python)

I have a dictionary and I would like to get the key whose value is the minimum nonzero.

E.g. given the input:

{1:0, 2:1, 3:2}

It would return 2.

like image 297
Konstantina K. Avatar asked Dec 14 '22 15:12

Konstantina K.


1 Answers

You can do it on one iteration.

d = {1:0, 2:1, 3:2}

# Save the minimum value and the key that belongs to it as we go
min_val = None
result = None
for k, v in d.items():
    if v and (min_val is None or v < min_val):
        min_val = v
        result = k

print(result)

Some assumptions:

  • Negative values will be considered
  • It will return the first key that found
  • If it helps, min_val will hold the minimum value
like image 84
Maor Refaeli Avatar answered Dec 26 '22 14:12

Maor Refaeli