Home > Mobile >  Comparing dictionary of list of dictionary/nested dictionary
Comparing dictionary of list of dictionary/nested dictionary

Time:11-24

There are two dict main and input, I want to validate the "input" such that all the keys in the list of dictionary and nested dictionary (if present/all keys are optional) matches that of the main if not the wrong/different key should be returned as the output.

main = "app":[{
    "name": str,
    "info": [
        {
        "role": str,
        "scope": {"groups": list}
        }
        ]
    },{
    "name": str,
    "info": [
        {"role": str}
            ]
}]

input_data = "app":[{
    'name': 'nms',
    'info': [
        {
        'role': 'user',
        'scope': {'groups': ['xyz']
                }
        }]
},{
    'name': 'abc', 
    'info': [
    {'rol': 'user'}
    ]
}]

when compared input with main the wrong/different key should be given as output, in this case

['rol']

CodePudding user response:

The schema module does exactly this. You can catch SchemaUnexpectedTypeError to see which data doesn't match your pattern.

Also, make sure you don't use the word input as a variable name, as it's the name of a built-in function.

CodePudding user response:

keys = []
def print_dict(d):
    if type(d) == dict:
        for val in d.keys():
            df = d[val]
            try:
                if type(df) == list:
                    for i in range(0,len(df)):
                        if type(df[i]) == dict:
                            print_dict(df[i])
            except AttributeError:
                pass
            keys.append(val)
    else:
        try:
            x = d[0]
            if type(x) == dict:
                print_dict(d[0])
        except:
            pass
    return keys
keys_input = print_dict(input)
keys = []
keys_main = print_dict(main)
print(keys_input)

print(keys_main)

for i in keys_input[:]:
        if i in keys_main:
            keys_input.remove(i)
print(keys_input)

This has worked for me. you can check above code snippet and if any changes provide more information so any chances if required.

  • Related