如何检查python字典内的内部字典中是否存在键? [英] How to check if a key exists in an inner dictionary inside a dictionary in python?
本文介绍了如何检查python字典内的内部字典中是否存在键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个python字典:
There is a python dictionary:
a = {b:{c:{"x":1, "y":2, "z":3}}}
我想知道 a [b] [c] ["z"]
是否存在,但我不知道 a [b] [c]
或 a [b]
是否存在.
I want to know if a[b][c]["z"]
exists,
but yet I don't know if a[b][c]
or a[b]
exist either.
所以,如果我这样做:
if "z" in a[b][c]:
我可能会收到"a [b]"
中不存在键c或"a"
错误中不存在键b.
I may get a "key c doesn't exist in a[b]"
or "key b doesn't exist in a"
error.
在这种情况下,如何正确检查a [b] [c]中是否存在z?
How to properly check if z exists in a[b][c] in this case?
推荐答案
如果由于某种原因(例如lambda func,列表理解,生成器表达式等)而无法使用异常
IF you can't use an exception for some reason (eg. lambda func, list comprehension, generator expression etc)
value = a.get(b, {}).get(c, {}).get("z", None)
但是通常您应该更喜欢使用异常处理程序
But normally you should prefer to use the exception handler
这篇关于如何检查python字典内的内部字典中是否存在键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文