0

I am new to python. In Python, I want to compare two list 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:

List

1 = [{"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.

Storyfoyo
  • 15
  • 3
  • 1
    here is an example how it could work https://stackoverflow.com/questions/27265939/comparing-python-dictionaries-and-nested-dictionaries – thomkell Jun 28 '22 at 12:14

1 Answers1

0

Here is my solution:

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

list_2 = [
{"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"}]

list_1_keys = [sorted(element.keys())[0] for element in list_1]

res = [element for element in list_2 if sorted(element.keys())[0] not in list_1_keys]

I think you do not need any check on the key zrepcode because this is always the same.

let's me know if you need more explanation/details about the solution.

I hope it will help you.

EDIT

here is the solution if we take into account the zrepcode

list_1_couple = []
for element in list_1:
    keys = sorted(element.keys())
    list_1_couple.append([keys[0], element[keys[1]]])

res = []
for element in list_2:
    keys = sorted(element.keys())
    if [keys[0], element[keys[1]]] not in list_1_couple:
        res.append(element) 

print(res)

You can probably clean a bit the code, but at least it should works

EDIT 2

If you prefer to use some one-liner

list_1_couple = [[sorted(element.keys())[0], element[sorted(element.keys())[1]]] for element in list_1 ]

res = [element for element in list_2 if [sorted(element.keys())[0], element[sorted(element.keys())[1]]] not in list_1_couple] 

will do the trick too

Diane Delallée
  • 123
  • 2
  • 9