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


i'm trying key lowest value in dictionary key in separate list. fear initializing variable "key" in way might cause trouble in future, though don't think will.

d = { "a":3, "b":2, "c":7 } l = ["a","b"]  key = l[0] c in l:     key = c if d[c] < d[key] else key print key 

i'm still trying handle on list comprehension. have tried replace loop , everything, didn't work:

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

ended invalid syntax error.

use key parameter min() function pick out lowest key:

min(l, key=d.__getitem__) 

the key parameter must callable maps items in input list value want pick minimum item. in example, 'b' lowest item because d maps 2, while 'a' mapped 3.

demo:

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

if there value in l not listed in d, d.__getitem__ raise keyerror:

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

you use lambda i: d[i] same effect without scary direct use of dunder (double-underscore) special methods.

if want ignore non-existent keys, use:

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

float('inf') guaranteed larger other number, in above example 'e' not considered minimum because doesn't exist in d.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -

matlab - How to equate a structure array to structure array -