python字典结构_如何在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)

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值