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?
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
                        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'
                        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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With