'given the same sub key of a nested dictionary, subtract corresponding keys

I have a dictionary dct with two sets set1 and set2 of different lengths.

dct ={
        "id": "1234",
        "set1": [
            {
                "sub_id": "1234a",
                "details": [
                    {
                        "sum": "10",
                        "label": "pattern1"
                    }
                ],                          
            },
            {
                "sub_id": "1234b",
                "details": [
                    {
                        "sum": "10",
                        "label": "pattern3"
                    }
                ],                          
            } 
        ],                                            
        "set2": [                                  
            {                                         
                "sub_id": "3463a",
                "details": [                           
                    {                                 
                        "sum": "20",
                        "label": "pattern1"
                    }                                 
                ],
            },
            {                                         
                "sub_id": "3463b",
                "details": [                           
                    {                                 
                        "sum": "100",
                        "label": "pattern2"
                    }                                 
                ],
            },
            {
                "sub_id": "3463c",
                "details": [
                    {
                        "sum": "100",
                        "label": "pattern3"
                    }
                ],                          
            }
        ]
    }

I need to check for each label if the corresponding sum has changed, and if yes, subtract these.

pairs1=[]
pairs2=[]
for d in dct['set1']:
    for dd in d['details']:
        pairs1.append((dd['label'],dd['sum']))
for d in dct['set2']:
    for dd in d['details']:
        pairs2.append((dd['label'],dd['sum']))
result={}
for p in pairs1:
    for pp in pairs2:
        if p[0] == pp[0]:
            result[p[0]]= int(pp[1])-int(p[1])
result

Output something like:

{'pattern1': 10, 'pattern3': 90}

Is there a better way to iterate through the nested 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