Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   RE: Dict comprehension help (http://www.velocityreviews.com/forums/t955194-re-dict-comprehension-help.html)

Peter Otten 12-06-2012 10:45 AM

RE: Dict comprehension help
 
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]



All times are GMT. The time now is 05:45 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57