3

I have a dictionary:

d = {'a': (1, 2, 'a'), 'b': (1, 2, 'b'), 'c': (2, 4, 'c'), 'd': (1, 3, 'd'), 'e': (0, 1, 'e'), 'f': (0, 1, 'f'), 'g': (1, 3, 'g'), 'h': (0, 1, 'h'), 'j': (1, 2, 'j'), 'i': (0, 1, 'i'), 'k': (-1, 0, 'k')}

And I want to find which one is the minimum of all the values in the dictionary. However, on the last key (k) there is a -1.

How can I ignore that key/value without removing it? Or is the only way to remove :

'k': (-1, 0, 'k')

and then use min().

Here is my code:

print(min(d.values()))

Current output:

(-1, 0, 'k')

Expected output:

(0, 1, 'e')

3 Answers3

8

You can "filter" tuples that start with negatives out and not include them when you call min:

d = {'a': (1, 2, 'a'), 'b': (1, 2, 'b'), 'c': (2, 4, 'c'), 'd': (1, 3, 'd'), 'e': (0, 1, 'e'), 'f': (0, 1, 'f'), 'g': (1, 3, 'g'), 'h': (0, 1, 'h'), 'j': (1, 2, 'j'), 'i': (0, 1, 'i'), 'k': (-1, 0, 'k')}

print(min(tup for tup in d.values() if tup[0] >= 0))

Output:

(0, 1, 'e')
iz_
  • 15,923
  • 3
  • 25
  • 40
3

You can do this by passing in a key function to min that forces the negative values to rank higher:

min(d.values(), key=lambda x: (x[0]<0, x))
#(0, 1, 'e')

For the negative values, x[0]<0 will be 1 so they will sort higher than the positive values. Finally for the positive values, x will be used to find the min.

pault
  • 41,343
  • 15
  • 107
  • 149
1

Another variant is to use filter function:

min(filter(lambda x: x[0] >= 0, d.values()))
Sergii Dymchenko
  • 6,890
  • 1
  • 21
  • 46