Arun
Arun

Reputation: 831

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.

Upvotes: 4

Views: 5946

Answers (2)

Ron Nabuurs
Ron Nabuurs

Reputation: 1556

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]

Upvotes: 7

Smart Manoj
Smart Manoj

Reputation: 5851

for k,i in enumerate(list(list_dict)):
    if i['folder'] in remove_folder_list:
        del list_dict[list_dict.index(i)]

print(list_dict)

Upvotes: 0

Related Questions