我需要一种方法来获得字典值,如果它的键存在,或简单地返回None,如果它不存在。

然而,如果你搜索一个不存在的键,Python会引发一个KeyError异常。我知道我可以检查钥匙,但我在寻找更明确的东西。如果键不存在,是否有一种方法只返回None ?


当前回答

如果你有一个更复杂的需求,等价于缓存,这个类可能会派上用场:

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

其他回答

您应该使用dict类中的get()方法

d = {}
r = d.get('missing_key', None)

这将导致r == None。如果在字典中没有找到键,get函数返回第二个参数。

我被python2 vs python3的功能吓了一跳。我将根据我最终为python3所做的工作来回答这个问题。我的目标很简单:检查字典格式的json响应是否出错。我的字典叫“令牌”,我要找的键是“错误”。我正在寻找键“错误”,如果它不在那里设置为None的值,然后检查是值为None,如果是这样,继续我的代码。如果我确实有键“错误”,else语句将处理。

if ((token.get('error', None)) is None):
    do something

给那些使用字典的人。获取嵌套字典的技术,而不是显式地检查字典的每一层,或扩展dict类,您可以将默认返回值设置为除最外层之外的空字典。这里有一个例子:

my_dict = {'level_1': {
             'level_2': {
                  'level_3': 'more_data'
                  }
              }
           }
result = my_dict.get('level_1', {}).get('level_2', {}).get('level_3')
# result -> 'more_data'
none_result = my_dict.get('level_1', {}).get('what_level', {}).get('level_3')
# none_result -> None

警告:请注意,此技术仅在预期键值为字典时有效。如果键what_level确实存在于字典中,但它的值是字符串或整数等,那么它将引发AttributeError。

如果你有一个更复杂的需求,等价于缓存,这个类可能会派上用场:

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

正如上面其他人所说,您可以使用get()。

但要检查密钥,你还可以这样做:

d = {}
if 'keyname' in d:

    # d['keyname'] exists
    pass

else:

    # d['keyname'] does not exist
    pass