python模式具有至少一个键 [英] python schema to have at least one key
本文介绍了python模式具有至少一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用> schema
库.
如何创建模式以验证字典中是否包含任何键和相应的值?
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,
})
目前所有键都是Optional
,但我希望至少有一个.
At the moment the keys are all Optional
, but I want there to be at least one of them.
推荐答案
上下文
- python2
- 使用架构库进行验证
- DevSyedK想创建一个模式验证约束,该约束要求字典从一组可能的键中至少拥有一个键
- DevSyedK当前具有
ZeroOrMore
约束,但DevSyedK希望它成为OneOrMore
约束 - 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 - 建立两个列表,一个列表包含所有可能的密钥,另一个列表包含要验证的数据中包含的实际密钥
- 创建模式约束,当且仅当两个列表的交集为非空时才返回
True
-
注意:这不是问题的完整解决方案,只是概念证明.
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] )
这篇关于python模式具有至少一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文