有一个python字典:
a = {b:{c:{"x":1, "y":2, "z":3}}}
我想知道 a[b][c]["z"] 是否存在, 但我不知道 a[b][c] 或 a[b] 是否存在。
所以,如果我这样做:
if "z" in a[b][c]:
我可能会得到一个 "key c doesn't exist in a[b]" 或 "key b doesn't exist in a" 错误。
在这种情况下,如何正确检查 z 是否存在于 a[b][c] 中?
请您参考如下方法:
Python 的方式是根本不用检查。
try:
value = a[b][c]["z"]
# do something with value
except KeyError:
print 'Sorry wrong key'
这里 a,b,"z"的任意组合可能不在字典中,但它们都会被异常处理程序捕获。 OTH,存在确切 key 的情况将导致您的其余代码被执行。
您可能还想考虑使用 defaultdict
The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
这使您确信像 a[b][c]["z"] 这样的符号将始终无错误地执行,并且在某些情况下可能有用,特别是在您试图避免的情况下样板代码。
