如果键存在,我需要一种获取字典值的方法,否则只返回None
。
然而,如果搜索不存在的键,Python会引发一个KeyError
异常。我知道我可以检查键是否存在,但我正在寻找更明确的方法。是否有一种方式,如果键不存在,就只返回None
?
如果键存在,我需要一种获取字典值的方法,否则只返回None
。
然而,如果搜索不存在的键,Python会引发一个KeyError
异常。我知道我可以检查键是否存在,但我正在寻找更明确的方法。是否有一种方式,如果键不存在,就只返回None
?
d1={"One":1,"Two":2,"Three":3}
d1.get("Four")
try:
value = dict['keyname']
except IndexError:
value = None
Python2和Python3的差异让我大吃一惊。我会基于我在Python3中所做的内容进行回答。我的目标很简单:检查字典格式的JSON响应是否出现错误。我的字典名为“token”,我要查找的关键字是“error”。我正在寻找关键字“error”,如果它不存在,则将其设置为None的值,然后检查值是否为None,如果是,则继续执行我的代码。否则语句将处理如果我有关键字“error”的情况。
if ((token.get('error', None)) is None):
do something
class Cache(dict):
""" Provide a dictionary based cache
Pass a function to the constructor that accepts a key and returns
a value. This function will be called exactly once for any key
required of the cache.
"""
def __init__(self, fn):
super()
self._fn = fn
def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
value = self[key] = self._fn(key)
return value
def get_from_database(name):
# Do expensive thing to retrieve the value from somewhere
return value
answer = Cache(get_from_database)
x = answer(42) # Gets the value from the database
x = answer(42) # Gets the value directly from the dictionary
如果你可以使用False
完成它,那么还有hasattr内置函数:
e=dict()
hasattr(e, 'message'):
>>> False
.get(key)
代替[key]
。 - Gabe