我正在使用以下代码来验证一个字典(a)是否与另一个字典(check_against)相同。不幸的是,我的代码不太易读,所以我想知道是否有更快/更干净的内置解决方案来实现相同的结果。也许我只是没有搜索到正确的关键词,但我没有找到任何关于我认为是相当常见的任务的讨论。
check_against = {
'a' : str,
'b' : {
'c': int,
'd': int,
}
}
a = {
'a' : 1,
'c' : 1
}
def get_type_at_path(obj, chain):
_key = chain.pop(0)
if _key in obj:
return key_exists(obj[_key], chain) if chain else type(obj[_key])
def root_to_leaf_paths(tree, cur=()):
if isinstance(tree,dict):
for n, s in tree.items():
for path in root_to_leaf_paths(s, cur+(n,)):
yield path
else:
yield [cur,tree]
for path,value_type in root_to_leaf_paths(check_against):
a_value_type = get_type_at_path(a,list(path))
if a_value_type == None:
print(f"Missing key at path \"{list(path)}\"")
elif not a_value_type == value_type:
print(f"Value at path \"{list(path)}\" should be of type \"{value_type}\" but got {a_value_type}")
输出
Value at path "['a']" should be of type "<class 'str'>" but got <class 'int'>
Missing key at path "['b', 'c']"
Missing key at path "['b', 'd']"