如果字典键不可用,则返回 None [英] Return None if Dictionary key is not available
本文介绍了如果字典键不可用,则返回 None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果键存在,我需要一种方法来获取字典值,如果不存在,则直接返回None
.
I need a way to get a dictionary value if its key exists, or simply return None
, if it does not.
但是,如果您搜索不存在的键,Python 会引发 KeyError
异常.我知道我可以检查密钥,但我正在寻找更明确的东西.如果密钥不存在,有没有办法只返回 None
?
However, Python raises a KeyError
exception if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None
if the key does not exist?
推荐答案
您可以使用 dict.get()
value = d.get(key)
如果 key 不在 d
中,它将返回 None
.你也可以提供一个不同的默认值来代替 None
:
which will return None
if key is not in d
. You can also provide a different default value that will be returned instead of None
:
value = d.get(key, "empty")
这篇关于如果字典键不可用,则返回 None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文