Functional way to compare things inside a list

Chris Angelico rosuav at gmail.com
Fri Sep 21 04:23:34 EDT 2012


On Fri, Sep 21, 2012 at 8:58 AM,  <thorsopia at lavabit.com> wrote:
> Hi,
>
> list = [{'1': []}, {'2': []}, {'3': ['4', '5']}]
>
> I want to check for a value (e.g. '4'), and get the key of the dictionary
> that contains that value.
> (Yep, this is bizarre.)
>
> some_magic(list, '4')
> => '3'
>
> What's the functional way to do it?
> Is it possible to do it with a one-liner?

I'm thinking here of a list comprehension, filter(), and next() to
grab the first element. Let's see...

By the way, I wouldn't use 'list' as a variable name; you shadow the
built-in type.

lst = [{'1': []}, {'2': []}, {'3': ['4', '5']}]
def find_n(n,dic):
	for key,searchme in dic.items():
		if n in searchme: return key

next(filter(None,[find_n('4',x) for x in lst]))

That gets the result, but probably not in the cleanest way. I'm not
sure off-hand if Python has a convenient way to curry a function, but
if so, you could make the filter call rather simpler.

Note that this is written for Python 3, where filter() returns an
iterator, thus the algorithm is lazy and thus efficient (a very
Australian way to do things).

ChrisA
Proudly Australian, proudly lazy!



More information about the Python-list mailing list