Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > RE: Dict comprehension help

Reply
Thread Tools

RE: Dict comprehension help

 
 
Peter Otten
Guest
Posts: n/a
 
      12-06-2012
Joseph L. Casale wrote:

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

>
> Ugh, had part of that backwards Nice!
>
>> 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?

>
> The reason is that I need several of these in an init function and they
> stack up nicely where as the loops get unruly in length, but I don't
> disagree.


You could put the loop into a helper function, but if you are looping
through the same my_list more than once why not build a lookup table

my_dict = {d["key"]: d for d in my_list}

and then find the required dict with

my_dict[value]

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
RE: Dict comprehension help Joseph L. Casale Python 0 12-06-2012 03:32 PM
RE: Dict comprehension help Joseph L. Casale Python 0 12-06-2012 04:38 AM
Re: Dict comprehension help Ian Kelly Python 0 12-06-2012 03:38 AM
Dict comprehension help Joseph L. Casale Python 0 12-06-2012 03:03 AM
List comprehension in if clause of another list comprehension Vedran Furac( Python 4 12-19-2008 01:35 PM



Advertisments