Re: Functional way to compare things inside a list

Discussion in 'Python' started by Chris Angelico, Sep 21, 2012.

  1. On Fri, Sep 21, 2012 at 8:58 AM, <> 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!
    Chris Angelico, Sep 21, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. gf gf
    Replies:
    6
    Views:
    321
    Dave Benjamin
    Mar 5, 2005
  2. Replies:
    15
    Views:
    271
    Ramchandra Apte
    Sep 23, 2012
  3. Chris Rebert
    Replies:
    0
    Views:
    170
    Chris Rebert
    Sep 21, 2012
  4. Chris Angelico
    Replies:
    0
    Views:
    178
    Chris Angelico
    Sep 21, 2012
  5. Chris Rebert
    Replies:
    0
    Views:
    206
    Chris Rebert
    Sep 21, 2012
Loading...

Share This Page