您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Python中验证字典的结构(或架构)?

如何在Python中验证字典的结构(或架构)?

不使用库,您还可以定义一个简单的递归函数,如下所示:

def check_structure(struct, conf):
    if isinstance(struct, dict) and isinstance(conf, dict):
        # struct is a dict of types or other dicts
        return all(k in conf and check_structure(struct[k], conf[k]) for k in struct)
    if isinstance(struct, list) and isinstance(conf, list):
        # struct is list in the form [type or dict]
        return all(check_structure(struct[0], c) for c in conf)
    elif isinstance(struct, type):
        # struct is the type of conf
        return isinstance(conf, struct)
    else:
        # struct is neither a dict, nor list, not type
        return False

假设配置可以包含不在您的结构中的键,如您的示例。

更新:新版本还支持列表,例如 'foo': [{'bar': int}]

python 2022/1/1 18:27:36 有187人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶