PyDictChecker is a generic Python3 tool to run recursively through a dictionary and validate any kind of conditions in a given dictionary.
It is designed as a ''dictionary parser'' to verify element existence & value.
You can use ''human-readable'' rule to move on a node and check recursively and relatively any conditions (and sub-conditions).
Let's say you have the dictionary below:
music_library = {
'artists': [
{
'id': 1,
'real_name': {
'firstname': 'Jean - Philippe Léo',
'lastname': 'Smet'
},
'artist_name' : {
'firstname': 'Johnny',
'lastname': 'Hallyday',
},
'albums': [
{
'year': 1961,
'name': 'Salut les copains'
},
{
'year': 1961,
'name': 'Nous les gars, nous les filles'
},
{
'year': 1962,
'name': 'Sings Americas Rockin Hits'
}
]
}
]
}
If you want to verify if the last artist has at least one album:
_is_valid, _output_value = PyDictChecker.check(music_library, [
{
'path': 'artists->:last:->albums->:first:'
}
])
NB:
- ''_is_valid'' is valid in this case because the node exists
- ''_output_value'' is the first album in this case
If you want to check if:
- the first artist exists;
- and his real lastname is 'Smet';
- and his third album was published after 1961.
You can run the next method:
_is_valid, _output_value = PyDictChecker.check(music_library, [
{
'path': 'artists->:first:',
'conditions': [
{
'path': 'real_name->lastname',
'comparator': '==',
'comparative_value': 'Smet',
'cast_to': None,
'output': True
},
{
'path': 'albums->:pos:2->year',
'comparator': '>',
'comparative_value': 1960,
'cast_to': ':int:'
}
]
}
])
NB:
- please note that we use relative path in this case.
- the boolean ''_is_valid'' is valid and we get the value 'Smet' in ''_output_value''
See / run this test file py_dict_checker_test.py for more details.
So far, there are only these next comparators: '>'
, '<'
, '>='
, '<='
, '=='
, '!='
.
And these are the first operators:
- to cast a string to an integer, with
:int:
- to move into a dict:
:first:
,:last:
,:pos:X
(where X is the position of the element you want to move to)
$ python -m unittest discover -v -s . -p "*_test.py"
To create a build version in the "dist" directory
$ python setup.py sdist
This project is not listed on Pypi but you can import it from Github:
$ . venv/bin/activate
$ pip install -e git+https://github.com/thepocagency/pydictchecker.git#egg=pydictchecker
$ pip freeze > requirements.txt
Developed by Alexandre Veremme @ The POC Agency (cf. www.the-poc-agency.com)