Select Page

Problem

For a given list of dicts, find the first dict that matches the given criteria.

Consider the following list as an example and find the first dict with capital Mumbai.

[
  {
    'id': 'one',
    'state': 'Madhya Pradesh',
    'capital': 'Bhopal'
  },
  {
    'id': 'two',
    'state': 'Maharashtra',
    'capital': 'Mumbai'
  },
  {
    'id': 'three',
    'state': 'Karnataka',
    'capital': 'Bangalore'
  },
]

Using iterator to consume less memory

search_term = 'Mumbai'

searched_item = next(
 (item for item in item_list if item['capital'] == search_term),
 None
)

Using simple list comprehension

search_term = 'Mumbai'

searched_item = [item for item in item_list if item['capital'] == search_term][0]

Simpler for-else version

search_term = 'Mumbai'
searched_item = None
for item in item_list:
  if item['capital'] == search_term:
    searched_item = item
    break
else:
  searched_item = None

# in case searched_item cannot be
# initialied to None at the beginning,
# use the else clause