Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding key with minimum value in OrderedDict

I need to find the key whose value is the lowest in the ordered dictionary but only when it is True for the position in my_list.

from collections import OrderedDict

my_list = [True,False,False,True,True,False,False,False,]

my_lookup = OrderedDict([('a', 2), ('b', 9), ('c', 4), ('d', 7),  
                         ('e', 3), ('f', 0), ('g', -5), ('h', 9)])

I know how to do it with a for loop like

mins=[]
i=0
for item in my_lookup.items():
    if my_list[i]:
        mins.append(item)
    i+=1
print min(mins,key=lambda x:x[1])[0]

prints

a

because a is lowest that is also True in my_list.

This works but it is long and I want to know how to do it with comprehensions or one line?

like image 310
user2580667 Avatar asked Jul 14 '13 09:07

user2580667


3 Answers

You can use itertools.compress with key to min being get method,

>>> from itertools import compress
>>> min(compress(my_lookup, my_list), key=my_lookup.get)
a
like image 129
Jared Avatar answered Oct 17 '22 06:10

Jared


You can also combine generator expression and min:

>>> min(((value, key) for ((key, value), flag) in zip(my_lookup.iteritems(), my_list) if flag))[1]
'a'
like image 29
ovgolovin Avatar answered Oct 17 '22 07:10

ovgolovin


Two-liner:

from itertools import izip
print min((lookup_key for (lookup_key, keep) in izip(my_lookup.iterkeys(),
            my_list) if keep), key=my_lookup.get)
like image 42
martineau Avatar answered Oct 17 '22 06:10

martineau