How to find a value in a list of python dictionaries?

Question:

Have a list of python dictionaries in the following format. How would you do a search to find a specific name exists?

label = [{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
          'name': 'Test',
          'pos': 6},
             {'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
              'name': 'Name 2',
          'pos': 1}]

The following did not work:

if 'Test'  in label[name]

'Test' in label.values()
Asked By: bobsr

||

Answers:

You’d have to search through all dictionaries in your list; use any() with a generator expression:

any(d['name'] == 'Test' for d in label)

This will short circuit; return True when the first match is found, or return False if none of the dictionaries match.

Answered By: Martijn Pieters

You might also be after:

>>> match = next((l for l in label if l['name'] == 'Test'), None)
>>> print match
{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
 'name': 'Test',
 'pos': 6}

Or possibly more clearly:

match = None
for l in label:
    if l['name'] == 'Test':
        match = l
        break
Answered By: Eric
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.