I have a dictionary with config info:
JavaScript
x
11
11
1
my_conf = {
2
'version': 1,
3
4
'info': {
5
'conf_one': 2.5,
6
'conf_two': 'foo',
7
'conf_three': False,
8
'optional_conf': 'bar'
9
}
10
}
11
I want to check if the dictionary follows the structure I need.
I’m looking for something like this:
JavaScript
1
12
12
1
conf_structure = {
2
'version': int,
3
4
'info': {
5
'conf_one': float,
6
'conf_two': str,
7
'conf_three': bool
8
}
9
}
10
11
is_ok = check_structure(conf_structure, my_conf)
12
Is there any solution done to this problem or any library that could make implementing check_structure
more easy?
Advertisement
Answer
Without using libraries, you could also define a simple recursive function like this:
JavaScript
1
14
14
1
def check_structure(struct, conf):
2
if isinstance(struct, dict) and isinstance(conf, dict):
3
# struct is a dict of types or other dicts
4
return all(k in conf and check_structure(struct[k], conf[k]) for k in struct)
5
if isinstance(struct, list) and isinstance(conf, list):
6
# struct is list in the form [type or dict]
7
return all(check_structure(struct[0], c) for c in conf)
8
elif isinstance(conf, type):
9
# struct is the type of conf
10
return isinstance(struct, conf)
11
else:
12
# struct is neither a dict, nor list, not type
13
return False
14
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}]