Mahamutha M
Mahamutha M

Reputation: 1287

Compare two list of dictionary and delete a dictionary from a list if key and value exists

Based on the following two list of dictionaries, how to delete a dictionary in list1 based on a key("name") and value from list2?

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'}]

Upvotes: 0

Views: 45

Answers (1)

qwermike
qwermike

Reputation: 1486

You can use set to form the names you want to remove by. And then filter your first list.

Using comprehensions:

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

Using functional style:

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

Upvotes: 1

Related Questions