python schema to have at least one key

2019-08-13 16:26发布

问题:

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({
    Optional('name'): str,
    Optional('name_id'): int,
})

At the moment the keys are all Optional, but I want there to be at least one of them.

回答1:

Context

  • python2
  • validation with schema library

Problem

  • 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 a OneOrMore 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] )
    

See also

  • How to find list intersection?