'Python- How to find missed dictionary item by comparing two dictionary list

I am trying to find the missed dictionary element by comparing two dictionary list

list1=[{"amount":"1000",'dept':'marketing',"desig":"mgr",'id':'101'},
{"amount":"1331",'dept':None,"desig":"accnt",'id':'102'},{"amount":"1351",'dept':'mark',"desig":"sales",'id':'103'}]


list2=[{"amount":"1500",'dept':None,"desig":"mgr2",'id':'101'},
{"amount":"1451",'dept':'IT',"desig":"accnt",'id':'102'}]

difference=[item for item in list1 if item["id"] not in list2]

but its not giving the expected output for the missed key

expected output:

missed={"amount":"1351",'dept':'mark',"desig":"sales",'id':'103'}


Solution 1:[1]

Your edited question requires matching against the 'id' key, not the entire dictionary object as before. Since that is hashable, it is simplest to put it in a set to efficiently test whether something is part of the collection or not. (Edit: Credit @KellyBundy for suggesting set comprehension)

id_set = {item['id'] for item in list2}
difference = [item for item in list1 if item['id'] not in id_set]

difference here gives a list of all missing dictionaries. So to access all of them, you need to iterate over it.

for missed in difference:
    print(f'{missed=}')

and the output will be (it will print one line per dictionary)

missed={'amount': '1351', 'dept': 'mark', 'desig': 'sales', 'id': '103'}

If you know there will only be one missing item, or you only need the first element, you can use difference[0] to directly access the dictionary.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1