python - Filtering a list of dictionaries -


i have list of identical dictionaries

list_dict = [{'id': 1}, {'id': 2}, {'id': 3}] 

now want filter particular dictionary value of id id = 2

i do

list_filtered = [ dict dict in list_dict if dict['id'] == 2] 

above solution works if have long list inefficient iterate on whole list , check if id matches. other workarounds?

make generator expression , 1 match @ time, this

matcher = (d d in list_dict if d['id'] == 2) print next(matcher, none) 

when call next on same generator object, resume loop left, last time.

print next(matcher, none) 

the second argument next default value return if generator expression exhausted.


Comments

Popular posts from this blog

C# random value from dictionary and tuple -

cgi - How do I interpret URLs without extension as files rather than missing directories in nginx? -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -