从匹配值列表中删除dict

时间:2018-05-28 07:20:38

标签: python dictionary

我有一个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'} 
        ]

现在我要删除list_dict中包含remove_key_list

中所有值的字典
remove_key_list = ['INBOX','sent','Trash']

例如,我想从{'children': [], 'folder': 'INBOX', 'parent': 'None'}删除list dict并返回list dict

我是python的新手,如何在这里使用dellamda函数。

2 个答案:

答案 0 :(得分:3)

如果您只想删除与您folder之一相同的remove_key_list的字母,则应该执行此操作。

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]

答案 1 :(得分:0)

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)