Reputation: 111
I need to separate a tuple based on a value from a nested dictionary as below and put it in another list. I want to separate tuple with values 'bb'
original_list= [[('aa','1'),('bb','2')],[('cc','3'),('bb','4')],[('dd','5'),('dd','6')]]
I need two lists as below,
final_list= [[('aa','1')],[('cc','3')],[('dd','5'),('dd','6')]]
deleted_list = [[('bb','2')],[('bb','4')]]
I used the following recursive code,
def remove_items(lst, item):
r = []
for i in lst:
if isinstance(i, list):
r.append(remove_items(i, item))
elif item not in i:
r.append(i)
return r
It could produce the result list after deleting the value. Is there a way to get another list with the deleted values?
Upvotes: 1
Views: 106
Reputation: 16053
>>> def remove_items(lst, item):
... r = []
... d = []
... for i in lst:
... if isinstance(i, list):
... r_tmp,d_tmp = remove_items(i, item)
... if r_tmp:
... r.append(r_tmp)
... if d_tmp:
... d.append(d_tmp)
... else:
... if item not in i:
... r.append(i)
... else:
... d.append(i)
... return r,d
...
>>> original_list= [[('aa','1'),('bb','2')],[('cc','3'),('bb','4')],[('dd','5'),('dd','6')]]
>>> result = remove_items(original_list,'bb')
>>> result[0]
[[('aa', '1')], [('cc', '3')], [('dd', '5'), ('dd', '6')]]
>>> result[1]
[[('bb', '2')], [('bb', '4')]]
>>>
Upvotes: 1