Remove object from list, if Key of object in list = value1 and object to drop Key = value 2

Trying to do something like the following:

a = [{'fruit':'apple', 'color':'red'}, {'fruit':'pear', 'color':'blue'}, {'fruit':'pineapple', 
'color':'green'}]

for object in a:
    if 'pineapple' or 'pear' in object['fruit']:
         if 'pear' in object['fruit']:
             a.remove(object)

I tried something like this but it deletes every pear every time. I need it to only remove the object with ‘pear’ from the list, if an apple or pineapple object is present. If a pear object is by itself, I need it to not be removed. I’m guessing it is iterating through the same object but I’m not sure how to write it out.

Thanks

>Solution :

First check the pineapple condition:

if any('pineapple' in o['fruit'] for o in a):

and then rebuild a according to the pear criteria (don’t try to remove items from a while iterating over it, just build a new list):

    a = [o for o in a if 'pear' not in o['fruit']]

All together:

>>> a = [{'fruit':'apple', 'color':'red'}, {'fruit':'pear', 'color':'blue'}, {'fruit':'pineapple',
... 'color':'green'}]
>>>
>>> if any('pineapple' in o['fruit'] for o in a):
...     a = [o for o in a if 'pear' not in o['fruit']]
...
>>> a
[{'fruit': 'apple', 'color': 'red'}, {'fruit': 'pineapple', 'color': 'green'}]

Leave a Reply