Hyperion
Hyperion

Reputation: 2625

Remove dictionary from list with multiple conditions

list1 = [
   {'id': 1, 'country': 'Italy'},
   {'id': 2, 'country': 'Spain'},
   {'id': 3, 'country': 'Japan'}
]

I use this code to remove from list1 every dictionary that has country != Italy:

list2 = [element for element in list1 if element['country'] == 'Italy']

But I to include in list2 dictionaries which country == 'Italy' AND country == 'Spain' and remove all the others (or even better pop them from list1 without creating another one). How can I do this in one line=

Upvotes: 0

Views: 82

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

If you really want a one-liner, you can use a list comprehension with an in-place list update:

list1[:] = [d for d in list1 if d['country'] in ('Spain', 'Italy')]

Upvotes: 1

Related Questions