Re: Dict comprehension help

Discussion in 'Python' started by Ian Kelly, Dec 6, 2012.

  1. Ian Kelly

    Ian Kelly Guest

    On Wed, Dec 5, 2012 at 8:03 PM, Joseph L. Casale
    <> wrote:
    > I get a list of dicts as output from a source I need to then extract various dicts
    > out of. I can easily extract the dict of choice based on it containing a key with
    > a certain value using list comp but I was hoping to use dict comp so the output
    > was not contained within a list.
    >
    > reduce(lambda x,y: dict(x.items() + y.items()), filter(lambda z: z['key'] == value, my_list))
    >
    > where my_list is a list of dicts. The premise is all dicts in the list have a unique
    > value for z['key'].
    >
    > Anyone have a pointer as to how I might tackle this without lambdas and only
    > using dict comp?


    {k: v for d in my_list if d['key'] == value for (k, v) in d.items()}

    However, since you say that all dicts have a unique value for
    z['key'], you should never need to actually merge two dicts, correct?
    In that case, why not just use a plain for loop to search for the
    dict?

    for d in my_list:
    if d['key'] == value:
    result = d
    break
    else:
    raise ValueError("Value not found!")
    Ian Kelly, Dec 6, 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. Vedran Furac(
    Replies:
    4
    Views:
    322
    Marc 'BlackJack' Rintsch
    Dec 19, 2008
  2. Joseph L. Casale

    Dict comprehension help

    Joseph L. Casale, Dec 6, 2012, in forum: Python
    Replies:
    0
    Views:
    122
    Joseph L. Casale
    Dec 6, 2012
  3. Joseph L. Casale

    RE: Dict comprehension help

    Joseph L. Casale, Dec 6, 2012, in forum: Python
    Replies:
    0
    Views:
    116
    Joseph L. Casale
    Dec 6, 2012
  4. Peter Otten

    RE: Dict comprehension help

    Peter Otten, Dec 6, 2012, in forum: Python
    Replies:
    0
    Views:
    151
    Peter Otten
    Dec 6, 2012
  5. Joseph L. Casale

    RE: Dict comprehension help

    Joseph L. Casale, Dec 6, 2012, in forum: Python
    Replies:
    0
    Views:
    130
    Joseph L. Casale
    Dec 6, 2012
Loading...

Share This Page