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



有两个字典main和input,我想验证一下"input"这样,字典和嵌套字典列表中的所有键(如果存在/所有键都是可选的)如果不是错误的/不同的键,则应作为输出返回与主键匹配的键。

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'}
]
}]

当输入与主键比较时,错误/不同的键应该作为输出,在这种情况下

['rol']

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

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

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应该会产生正确的输出。尝试添加大括号"{"/"}"围绕你的字典。它应该看起来像这样:

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

最新更新