本文介绍了如果字典键不可用,则不返回任何值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种方法来获取字典值(如果它的键存在),或者简单地返回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()
You can use dict.get()
value = d.get(key)
,如果key is not in 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")
这篇关于如果字典键不可用,则不返回任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!