Home > OS >  python: preserve certain values when removing from a nested list
python: preserve certain values when removing from a nested list

Time:03-30

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:

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'}]]

CodePudding user response:

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

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

CodePudding user response:

Try this:

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'}]]
new_list = []
new_list.extend([i for i in my_list if i[1]['speaker'] != "gold" ])
  • Related