Comparing two nested dictionary to write in list comprehension method

Viewed 37

The code below works fine for comparing these two types of nested dictionaries. Is it possible to write this in list comprehension? or any other way that is easier to understand

dict1 = {
           'Texture': {'actual': 1.0 , 'simulated': 3}, 
           'Detector': {'SumAmp': 1.0}, 
           'color': {'blue': 0.0001}, 
           'Compton': {'Amplitude': 10000.0}}
dict2 = {
"Color": {
            "Red": { "range": (-1, 1),
        },
           "Green": {
                      "range": (0, 0.1),
        },
           "Blue": {
                     "range": (-0.01, 0.001),
        },
    },
"Texture": {
        "actual": {"range": (4, 3),
        },
        "simulated": {"range": (-2, 2),
        },
        "abstract": {"range": (20, 50),
        },
        "invented_texture": { "range": (-6, 6),
        },
    },

```     L = []
        # Check to see if dict1 keys are similar with dict2
        for k, v in dict1.items():
            for k2, v2 in dict2.items():
                if k == k2:
                    for k4, v4 in v.items():
                        for k3, v3 in v2.items():
                                if k4 == k3:
                                     L.append(v3["range"])

1 Answers

We will do

[dict2[key11][key12]['range'] 
 for key11, value11 in dict1.items() 
 for key12 in value11 
 if key11 in dict2 and key12 in dict2[key11]]
#[(4, 3), (-2, 2)]
Related