0

I have a list of objects and I want to only return objects that have a field that contains a certain value.

Is there a more terse/pythonic way of doing this:

list-o-dicts = get-my-objects()

for dict in list-o-dicts:
    if 'mystring' in dict['myfield']:
        pprint( dict )

Does python have a cool, sugary, shortcut for doing this?

red888
  • 27,709
  • 55
  • 204
  • 392
  • 2
    I suppose you could use a list comprehension if you wanted to sugar it up for no good reason: `output = [dict for dict in list-o-dicts if 'mystring' in dict['myfield']]` – Blorgbeard Nov 27 '17 at 23:52

1 Answers1

0

Try filter:

filter(lambda x: 'mystring' in x['myfield'], list-o-dicts)
Galen
  • 1,307
  • 8
  • 15