我需要一种方法来获取字典值(如果它的键存在),或者简单地返回None,如果它不存在。但是,KeyError如果您搜索不存在的键,Python会引发异常。我知道我可以检查密钥,但是我正在寻找更明确的密钥。None如果密钥不存在,是否有办法返回?
3 回答

凤凰求蛊
TA贡献1825条经验 获得超4个赞
您可以使用 dict.get()
value = d.get(key)
None如果将返回key is not in d。您还可以提供将返回的其他默认值,而不是None:
value = d.get(key, "empty")

子衿沉夜
TA贡献1828条经验 获得超3个赞
别再奇怪了。它内置在语言中。
>>>帮助(dict)
模块内置的类字典帮助:
类dict(object)
| dict()->新的空字典
| dict(mapping)->从映射对象的字典初始化的新字典
| (键,值)对
...
|
| 得到(...)
| D.get(k [,d])-> D [k]如果D中有k,否则为d。d默认为无。
|
...

POPMUISE
TA贡献1765条经验 获得超5个赞
如果您想要一个更透明的解决方案,则可以继承dict此行为:
class NoneDict(dict):
def __getitem__(self, key):
return dict.get(self, key)
>>> foo = NoneDict([(1,"asdf"), (2,"qwerty")])
>>> foo[1]
'asdf'
>>> foo[2]
'qwerty'
>>> foo[3] is None
True
添加回答
举报
0/150
提交
取消