python schema to have at least one key

[亡魂溺海] 提交于 2019-12-11 08:36:46

问题


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?


来源:https://stackoverflow.com/questions/45346374/python-schema-to-have-at-least-one-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!