Home > Mobile >  Removing elements from list of dictionaries based on condition
Removing elements from list of dictionaries based on condition

Time:10-25

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:

  • If match = 2 or 1, keep only the dictionaries with match = 2 or 1.

  • If match = 0, make new list empty.

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?

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

You can use list_comprehensions.

# if you want only keep '1' and '2'
lst = [dct for dct in lst if dct.get('match') in [1,2]]

# Or If you want to delete '0'
lst = [dct for dct in lst if dct.get('match') != 0]

print(lst)

Output:

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

CodePudding user response:

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)
  • Related