Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate structure (or schema) of dictionary in 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?

like image 872
Thyrst' Avatar asked Aug 22 '17 08:08

Thyrst'


People also ask

What is the structure of dictionary in Python?

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.

How do you validate a datatype in Python?

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 ...


1 Answers

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)) 
like image 196
Danil Speransky Avatar answered Oct 05 '22 19:10

Danil Speransky