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


Groups > comp.lang.python > #29606 > unrolled thread

Re: Functional way to compare things inside a list

Started byChris Angelico <rosuav@gmail.com>
First post2012-09-21 18:23 +1000
Last post2012-09-21 18:23 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#29606 — Re: Functional way to compare things inside a list

FromChris Angelico <rosuav@gmail.com>
Date2012-09-21 18:23 +1000
SubjectRe: Functional way to compare things inside a list
Message-ID<mailman.992.1348215817.27098.python-list@python.org>
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!

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web