繁体   English   中英

比较字典列表/嵌套字典的字典

[英]Comparing dictionary of list of dictionary/nested dictionary

有两个 dict main 和 input,我想验证“输入”,以便字典和嵌套字典列表中的所有键(如果存在/所有键都是可选的)匹配 main 的键,如果不是错误/不同的键应作为 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'}
    ]
}]

将输入与 main 进行比较时,错误/不同的密钥应为 output,在这种情况下

['rol']

模式模块正是这样做的。 您可以捕获SchemaUnexpectedTypeError以查看哪些数据与您的模式不匹配。

另外,请确保不要使用单词input作为变量名,因为它是内置 function 的名称。

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)

这对我有用。 您可以检查上面的代码片段,如果有任何更改,可以提供更多信息,以便在需要时提供任何机会。

字典和列表比较它们默认嵌套的内容。

input_data == main如果你正确地格式化你的字典,应该会得到正确的 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'}
    ]
}]}

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

比较结果应如下所示:

input_data2 == input_data # True
main == input_data # False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM