Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find dictionary key with the lowest value where key is in a list

Tags:

python

I'm trying to get the key with the lowest value in a dictionary where the key is in a separate list. I also fear that initializing my variable "key" in the way I am might cause trouble in the future, even though I don't think it will.

d = { "a":3, "b":2, "c":7 }
l = ["a","b"]

key = l[0]
for c in l:
    key = c if d[c] < d[key] else key
print key

I'm still trying to get a handle on list comprehension. I have tried something like this to replace the for loop and everything, but it didn't work:

key = c if d[c] < d[key] else key for c in l

Ended with an invalid syntax error.

like image 558
PoDuck Avatar asked Jan 27 '26 13:01

PoDuck


1 Answers

Use the key parameter to the min() function to pick out a lowest key:

min(l, key=d.__getitem__)

The key parameter must be a callable that maps items in the input list to a value by which you want to pick the minimum item. In your example, 'b' is the lowest item because d maps it to 2, while 'a' is mapped to 3.

Demo:

>>> d = { "a":3, "b":2, "c":7 }
>>> l = ["a","b"]
>>> min(l, key=d.__getitem__)
'b'

If there is any value in l that is not listed in d, d.__getitem__ will raise a KeyError:

>>> min(['a', 'b', 'e'], key=d.__getitem__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'e'

You could also use lambda i: d[i] to get the same effect without scary direct use of dunder (double-underscore) special methods.

If you want to ignore non-existent keys, use:

min(['a', 'b', 'e'], key=lambda i: d.get(i, float('inf'))

float('inf') is guaranteed to always be larger than any other number, so in the above example 'e' will not be considered a minimum because it doesn't exist in d.

like image 86
Martijn Pieters Avatar answered Jan 29 '26 06:01

Martijn Pieters