bobsr
bobsr

Reputation: 3955

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

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()

Upvotes: 41

Views: 59026

Answers (2)

Eric
Eric

Reputation: 97571

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

Upvotes: 41

Martijn Pieters
Martijn Pieters

Reputation: 1121894

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.

Upvotes: 62

Related Questions