【发布时间】:2017-10-04 21:28:22
【问题描述】:
我有一本结构如下的字典:
D = {
'rows': 11,
'cols': 13,
(i, j): {
'meta': 'random string',
'walls': {
'E': True,
'O': False,
'N': True,
'S': True
}
}
}
# i ranging in {0 .. D['rows']-1}
# j ranging in {0 .. D['cols']-1}
我想编写一个将任意对象作为参数并检查它是否具有该结构的函数。这是我写的:
def well_formed(L):
if type(L) != dict:
return False
if 'rows' not in L:
return False
if 'cols' not in L:
return False
nr, nc = L['rows'], L['cols']
# I should also check the int-ness of nr and nc ...
if len(L) != nr*nc + 2:
return False
for i in range(nr):
for j in range(nc):
if not ((i, j) in L
and 'meta' in L[i, j]
and 'walls' in L[i, j]
and type(L[i, j]['meta']) == str
and type(L[i, j]['walls']) == dict
and 'E' in L[i, j]['walls']
and 'N' in L[i, j]['walls']
and 'O' in L[i, j]['walls']
and 'S' in L[i, j]['walls']
and type(L[i, j]['walls']['E']) == bool
and type(L[i, j]['walls']['N']) == bool
and type(L[i, j]['walls']['O']) == bool
and type(L[i, j]['walls']['S']) == bool):
return False
return True
虽然它有效,但我一点也不喜欢它。有没有 Pythonic 的方式来做到这一点?
我只能使用标准库。
【问题讨论】:
-
我会考虑为您的字典写一个JSON Schema,然后使用Python module 来验证它。
-
我认为引发异常是一个更好的主意,只返回真或假,因为它在这里完成了许多测试。可能更容易知道为什么 dict 没有通过测试
-
@tzaman 将该字典转换为 JSON 会很棘手,因为其中一个键是元组,而 JSON 仅本机支持字符串作为对象键。您必须将元组编码为字符串,这可能会产生歧义(例如,如果被检查的对象具有与您用于元组的格式相同的字符串键),我认为这是无效的,但是 JSON除了编码为字符串的有效元组之外,验证器无法分辨它。
-
在比较类型时至少使用
is而不是==。
标签: python dictionary