searching a list of dictionaries for an element in a list.
siona at chiark.greenend.org.uk
Wed Aug 10 15:13:41 CEST 2005
Dan <dan at cellectivity.com> wrote:
>> [ someone else wrote: ]
>> I want to search list1, and the result should be all dictionaries where
>> primarycolor is in input. I can do this using a double for-loop, but is
>> there a more efficent way?
>Of course. :-)
>L = [dict for dict in list1 if dict['primarycolor'] in input]
Note that (1) shadowing builtin dict is a bad idea and (2) that's
still two nested loops -- I think you do theoretically better with
input_set = set(input)
output_list = [ d for d in dict_list if d['primarycolor'] in input_set ]
but I suspect input would have to be a rather large list to favour
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
More information about the Python-list