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

python: preserve certain values when removing from a nested list

I have a nested list as follows:

my_list = [['id_1', {'frame':[{'door': 'window', 'closet':'pinches'}], 'utterance':'sentence number 1', 'speaker':'silver'}],
 ['id_2',{'frame':[{'door': 'window', 'closet':'pinches'},{'door': 'new_door', 'closet':'hinges'}], 'utterance':'sentence number 2', 'speaker':'silver'}],
 ['id_3', {'frame':[{'door': 'window', 'closet':'pins'}], 'utterance':'sentence number 3', 'speaker':'gold'}]]

I would like to remove a list from my_list if it contains the value ‘gold’, so I have done the following.

removed =[i for i in [item[1] for item in my_list] if not(i['speaker'] == 'gold')]

print(removed) 
#output: [{'frame': [{'door': 'window', 'closet': 'pinches'}], 'utterance': 'sentence number 1', 'speaker': 'silver'}, {'frame': [{'door': 'window', 'closet': 'pinches'}, {'door': 'new_door', 'closet': 'hinges'}], 'utterance': 'sentence number 2', 'speaker': 'silver'}]

But I would like to preserve the ‘id_number’, so my desire output is:

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

my_new_list = [['id_1', {'frame':[{'door': 'window', 'closet':'pinches'}], 'utterance':'sentence number 1', 'speaker':'silver'}],
 ['id_2',{'frame':[{'door': 'window', 'closet':'pinches'},{'door': 'new_door', 'closet':'hinges'}], 'utterance':'sentence number 2', 'speaker':'silver'}]]

>Solution :

I think you just need to "switch" the 2 inline loops:

removed =[item for item in my_list if not(item[1]['speaker'] == 'gold')]
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