searching a list of dictionaries for an element in a list.

O

Odd-R.

If input is ['red','blue'],
list1 is [ {'primarycolor':'red', 'secondarycolor':'burgundee'},
{'primarycolor':'red', 'secondarycolor':'wine'},
{'primarycolor':'yellow','secondarycolor':'plain'},
{'primarycolor':'blue','secondarycolor':'ocean'}]

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?
 
D

Dan

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]

In older versions of Python, we would use the "filter" function, which
accomplishes the same thing.
 
S

Sion Arrowsmith

Dan said:
[ 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
this.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top