Assuming I have the following list:
array1 = ['A', 'C', 'Desk']
and another array that contains:
array2 = [{'id': 'A', 'name': 'Greg'},
{'id': 'Desk', 'name': 'Will'},
{'id': 'E', 'name': 'Craig'},
{'id': 'G', 'name': 'Johnson'}]
What is a good way to remove items from the list? The following does not appear to work
for item in array2:
if item['id'] in array1:
array2.remove(item)
You could also use a list comprehension for this:
>>> array2 = [{'id': 'A', 'name': 'Greg'},
... {'id': 'Desk', 'name': 'Will'},
... {'id': 'E', 'name': 'Craig'},
... {'id': 'G', 'name': 'Johnson'}]
>>> array1 = ['A', 'C', 'Desk']
>>> filtered = [item for item in array2 if item['id'] not in array1]
>>> filtered
[{'id': 'E', 'name': 'Craig'}, {'id': 'G', 'name': 'Johnson'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With