Home > Net >  How to compare two lists of dicts in Python and fetch difference
How to compare two lists of dicts in Python and fetch difference

Time:06-29

I am new to python. In Python, I want to compare two lists of dictionaries

Below are 2 list of dictionary I want to compare based on key which is "zrepcode" and id which is the number "1", "3", and "4"...

Code snippet is as follows:

List1 = [{"3":[{"period":"P13","value":10,"year":2022}],"zrepcode":"55"},{"1":[{"period":"P10","value":5,"year":2023}],"zrepcode":"55"}]

List2 = [{"1":[{"period":"P1","value":10,"year":2023},{"period":"P2","value":5,"year":2023}],"zrepcode":"55"},{"3":[{"period":"P1","value":4,"year":2023},{"period":"P2","value":7,"year":2023}],"zrepcode":"55"},{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]

After Comparision, we need the unique list of dictionary from list2.

res = [{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]

This is the expected output, Now I don't know how I get this.

CodePudding user response:

You can use list comprehension to filter a list.

[x for x in list if condition]

and any() to see if a list has any elements matching a condition

any(condition for y in list)

or in your case, since you want those that don't exist in the other

[x for x in list2 if not any(your_condition for y in list1)]

To check if two elements have the same zrepcode value you can just compare them like

x['zrepcode'] == y['zrepcode']

Since your other point of comparison is a key and there are only two keys in each, you can compare the keys of both

x.keys() == y.keys()

Combine everything

[x for x in list2 if not any(x['zrepcode'] == y['zrepcode'] and x.keys() == y.keys() for y in list1)]
  • Related