1

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.

dreftymac
  • 29,742
  • 25
  • 114
  • 177

1 Answers1

0

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

dreftymac
  • 29,742
  • 25
  • 114
  • 177