Here\'s the functionality I mean, and I do it pretty frequently so maybe I\'m just reimplementing a built-in that I haven\'t seen:
import itertools
def first
You essentially want to map example.get
on the sequence, and get the first true-ish value. For that, you can use filter
with the default filter function that does exactly that, and get the first of that using next
:
>>> example = {'answer': 42, 'bring': 'towel'}
>>> lst = ['dolphin', 'guide', 'answer', 'panic', 'bring']
>>> next(filter(None, map(example.get, lst)))
42
In Python 3, all these things are lazy, so the whole sequence isn’t iterated. In Python 2, you can use itertools to get the lazy versions of the builtins, imap and ifilter
I don't think there's a built in function to do what you want. There is an arguably more Pythonic way of doing what you're doing:
example = {'answer': 42, 'bring': 'towel'}
keys = ['dolphin', 'guide', 'answer', 'panic', 'bring']
print filter(lambda x: x, map(example.get, keys))[0]
The downside of this method is that it will iterate through the whole list, instead of breaking out at the first value. You also have to add extra checks to make sure the list isn't empty.
you can use next()
builtin and generator expression:
next(example[key]
for key in ['dolphin', 'guide', 'answer', 'panic', 'bring']
if key in example)
if you want to use predefined function, it might be better to use filter, which accepts function as the first argument (lambda in example):
next(itertools.ifilter(lambda txt: 'a' in txt, ['foo', 'bar']))