Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #29606

Re: Functional way to compare things inside a list

References <63673.77.105.185.196.1348181901.squirrel@lavabit.com>
Date 2012-09-21 18:23 +1000
Subject Re: Functional way to compare things inside a list
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.992.1348215817.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Sep 21, 2012 at 8:58 AM,  <thorsopia@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!

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Functional way to compare things inside a list Chris Angelico <rosuav@gmail.com> - 2012-09-21 18:23 +1000

csiph-web