Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: Functional way to compare things inside a list (http://www.velocityreviews.com/forums/t952487-re-functional-way-to-compare-things-inside-a-list.html)

 Chris Angelico 09-21-2012 08:23 AM

Re: Functional way to compare things inside a list

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!

 All times are GMT. The time now is 08:28 AM.