Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading