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?
Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.
The validation can be done in two different ways, that is by using a flag variable or by using try or except which the flag variable will be set to false initially and if we can find out that the input data is what we are expecting the flag status can be set to true and find out what can be done next based on the ...
You may use schema
(PyPi Link)
schema is a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types.
from schema import Schema, And, Use, Optional, SchemaError def check(conf_schema, conf): try: conf_schema.validate(conf) return True except SchemaError: return False conf_schema = Schema({ 'version': And(Use(int)), 'info': { 'conf_one': And(Use(float)), 'conf_two': And(Use(str)), 'conf_three': And(Use(bool)), Optional('optional_conf'): And(Use(str)) } }) conf = { 'version': 1, 'info': { 'conf_one': 2.5, 'conf_two': 'foo', 'conf_three': False, 'optional_conf': 'bar' } } print(check(conf_schema, conf))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With