比较两个字典列表,如果键和值存在,则从列表中删除字典

时间:2018-12-27 08:13:27

标签: python-3.x list dictionary

基于以下两个字典列表,如何基于key(​​“ name”)和list2中的值删除list1中的字典?

list1 = [{'name':'john','age':'12','gender':'male'},
         {'name':'sam', 'age':'11','gender':'male'},
         {'name':'tom', 'age':'12','gender':'male'},
         {'name':'elsa','age':'14','gender':'female'},
         {'name':'juhi','age':'13','gender':'female'}]


list2 = 
     [{'name':'tom','gender':'male','status':1,'subject':'english'},             
   {'name':'elsa','gender':'female','status':0,'subject':'english'}]


Expected_list = [{'name':'john','age':'12','gender':'male'},
         {'name':'sam', 'age':'11','gender':'male'},
         {'name':'juhi','age':'13','gender':'female'}]

1 个答案:

答案 0 :(得分:1)

您可以使用set来形成您要删除的名称。然后过滤您的第一个列表。

使用理解力:

names = {x['name'] for x in list2}
expected_list = [x for x in list1 if x['name'] not in names]

使用功能样式:

names = set(map(lambda x: x['name'], list2))
expected_list = list(filter(lambda x: x['name'] not in names, list1))