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