Python Schema To Have At Least One Key
I'm using the schema library. How can I create a schema to validate if a dictionary contains anyone of the keys and corresponding values in it? mydict_schema = Schema({ Optiona
Solution 1:
Context
- python2
- validation with schema library
Use-case
- DevSyedK wants to create a schema validation constraint that requires a dictionary to have at least one key from a set of possible keys
- DevSyedK currently has a
ZeroOrMore
constraint, but DevSyedK wants it to be aOneOrMore
constraint
Solution
- Establish two lists, one list with all possible keys, and the other list with the actual keys contained in the data to be validated
- Create a schema constraint that returns
True
if and only if the intersection of the two lists is non-empty
Demo code
Note: this is not a complete solution to the question, just a proof-of-concept.
lstkeys_possible = ['alpha','bravo','charlie'] lstkeys_actual = [] ## wont validate lstkeys_actual = ['zulu'] ## wont validate lstkeys_actual = ['alpha'] ## will validate Schema( lambda vinput: bool(set(vinput[0]) & set(vinput[1])) ).validate( [lstkeys_possible,lstkeys_actual] )
Post a Comment for "Python Schema To Have At Least One Key"