keeran_q789
keeran_q789

Reputation: 91

Removing elements from list of dictionaries based on condition

Suppose I have a list of dictionaries

lst = [{'match': 0,
  'ref_title': ['dog2', 'title1'],
  'matching_string': 'dog2',
  'display_string': 'dog2'},
 {'match': 0,
  'ref_title': ['dog2', 'cat'],
  'matching_string': 'dog2',
  'display_string': 'dog2'},
 {'match': 2,
  'ref_title': ['dog2', 'dog'],
  'matching_string': 'dog',
  'display_string': 'dog2'}]

I am trying to make a new list, based on the following conditions:

So for the above case, I want to achieve

[{'match': 2,
  'ref_title': ['dog2', 'dog'],
  'matching_string': 'dog',
  'display_string': 'dog2'}]

How can I do this efficiently?

Upvotes: 1

Views: 958

Answers (3)

Yonas Kassa
Yonas Kassa

Reputation: 3690

try as follows:

match_finder checks if values 1 or 2 are in 'match' to satisfy your first condition. If this case is not satisfied it goes to check if match=0, which will return empty list.

lst = [{'match': 0,
'ref_title': ['dog2', 'title1'],
'matching_string': 'dog2',
'display_string': 'dog2'},
{'match': 0,
'ref_title': ['dog2', 'cat'],
'matching_string': 'dog2',
 'display_string': 'dog2'},
 {'match': 2,
  'ref_title': ['dog2', 'dog'],
  'matching_string': 'dog',
  'display_string': 'dog2'}]


def match_finder(lst):
    ks = [m['match'] for m in lst]

    if 1 in ks or 2 in ks:
        return [i for i in lst if i['match'] in {1,2}]
    elif 0 in ks:
        return []
    else:
        return None

match_finder(lst)

Upvotes: 0

Omer Dagry
Omer Dagry

Reputation: 567

lst = [{'match': 0,
  'ref_title': ['dog2', 'title1'],
  'matching_string': 'dog2',
  'display_string': 'dog2'},
 {'match': 0,
  'ref_title': ['dog2', 'cat'],
  'matching_string': 'dog2',
  'display_string': 'dog2'},
 {'match': 2,
  'ref_title': ['dog2', 'dog'],
  'matching_string': 'dog',
  'display_string': 'dog2'}]


new_lst = [dct for dct in lst if dct['match'] == 1 or dct['match'] == 2]
print(new_lst)

Upvotes: 2

Pierre D
Pierre D

Reputation: 26211

newlst = [d for d in lst if d.get('match') in {1,2}]

This also handles the corner case (spurious data) where some of the dicts were somehow missing a 'match' key.

Upvotes: 1

Related Questions