Reputation: 2625
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
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