本文介绍了如何在Python中验证字典的结构(或架构)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本包含配置信息的字典:

I have a dictionary with config info:

my_conf = {
    'version': 1,

    'info': {
        'conf_one': 2.5,
        'conf_two': 'foo',
        'conf_three': False,
        'optional_conf': 'bar'
    }
}

我想检查字典是否符合我需要的结构.

I want to check if the dictionary follows the structure I need.

我正在寻找这样的东西:

I'm looking for something like this:

conf_structure = {
    'version': int,

    'info': {
        'conf_one': float,
        'conf_two': str,
        'conf_three': bool
    }
}

is_ok = check_structure(conf_structure, my_conf)

有没有解决此问题的方法,或者有没有任何库可以使实现check_structure更加容易?

Is there any solution done to this problem or any library that could make implementing check_structure more easy?

推荐答案

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

Without using libraries, you could also define a simple recursive function like this:

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

这假定配置可以具有不在您的结构中的键,如您的示例.

This assumes that the config can have keys that are not in your structure, as in your example.

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

Update: New version also supports lists, e.g. like 'foo': [{'bar': int}]

这篇关于如何在Python中验证字典的结构(或架构)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:51