Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove dict from list of matching values

I have a list of dict,

list dict =  [
         {'children': [], 'folder': 'test2', 'parent': 'None'},
         {'children': [{'children': [], 'folder': 'arun2', 'parent': 'arun2'}],
          'folder': 'arun2',
          'parent': 'None'},
         {'children': [], 'folder': 'important', 'parent': 'None'},
         {'children': [], 'folder': 'arun', 'parent': 'None'},
         {'children': [], 'folder': 'hoi', 'parent': 'None'},
         {'children': [], 'folder': 'drafts', 'parent': 'None'},
         {'children': [], 'folder': 'Trash', 'parent': 'None'},
         {'children': [], 'folder': 'sent', 'parent': 'None'},
         {'children': [], 'folder': 'spam', 'parent': 'None'},
         {'children': [], 'folder': 'reference', 'parent': 'None'},
         {'children': [], 'folder': 'test3', 'parent': 'None'},
         {'children': [], 'folder': 'test1', 'parent': 'None'},
         {'children': [], 'folder': 'INBOX', 'parent': 'None'} 
        ]

Now i want to remove dict from list_dict that has all the values in the remove_key_list

remove_key_list = ['INBOX','sent','Trash']

For example i want remove {'children': [], 'folder': 'INBOX', 'parent': 'None'} from list dict and return the list dict

I'm new to python how to use del , lamda functions here.

like image 775
Arun Avatar asked Nov 06 '25 04:11

Arun


1 Answers

If you only want to remove the dicts that equals the folder to one of your remove_key_list this should do the job.

list_dict =  [
         {'children': [], 'folder': 'test2', 'parent': 'None'},
         {'children': [{'children': [], 'folder': 'arun2', 'parent': 'arun2'}],
          'folder': 'arun2',
          'parent': 'None'},
         {'children': [], 'folder': 'important', 'parent': 'None'},
         {'children': [], 'folder': 'arun', 'parent': 'None'},
         {'children': [], 'folder': 'hoi', 'parent': 'None'},
         {'children': [], 'folder': 'drafts', 'parent': 'None'},
         {'children': [], 'folder': 'Trash', 'parent': 'None'},
         {'children': [], 'folder': 'sent', 'parent': 'None'},
         {'children': [], 'folder': 'spam', 'parent': 'None'},
         {'children': [], 'folder': 'reference', 'parent': 'None'},
         {'children': [], 'folder': 'test3', 'parent': 'None'},
         {'children': [], 'folder': 'test1', 'parent': 'None'},
         {'children': [], 'folder': 'INBOX', 'parent': 'None'} 
        ]

filter_list = ['INBOX', 'sent', 'Trash']

filtered_list = [d for d in list_dict if d['folder'] not in filter_list]
like image 64
Ron Nabuurs Avatar answered Nov 08 '25 00:11

Ron Nabuurs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!