'Compare the keys of two nested dictionaries with level 3

I have two nested dictionary: main and test. I want to compare the keys of the dictionaries and find the difference.

main = {"A":{"AA":{"AAA1": [1, 3], "AAA2": [2,4]}, 'BB':  {'BBB1': [2 ,4 ], 'BBB2': [5,7]}}}

test1 = {"A":{"AA":{"AAA1": [3, 3], "AAA2": [4,4]}, 'BB':  {'BBB1': [4 ,4 ], 'BBB2': [7,7]}}}

test2 = {"A":{"AA":{"AAA1": [3, 3], "AAA2": [4,4]}, 'BB':  {'BBB1': [4 ,4 ]}}}

When comparing main and test1, the expected output is {} as all keys till level 3 are present.

When comparing main and test2, the expected output is {'A': {'BB': ['BBB2']}}.

I have tried the solution for three levels using the How to get the difference between two dictionaries in Python? Is there any other efficient method for nested dictionaries? Thanks in advance.



Sources

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

Source: Stack Overflow

Solution Source