如果字典键不可用,则返回None

问题:如果字典键不可用,则返回None

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

但是,KeyError如果您搜索不存在的键,Python会引发异常。我知道我可以检查密钥,但是我正在寻找更明确的密钥。None如果密钥不存在,是否有办法返回?

I need a way to get a dictionary value if its key exists, or simply return None, if it does not.

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?


回答 0

您可以使用 dict.get()

value = d.get(key)

None如果将返回key is not in d。您还可以提供将返回的其他默认值,而不是None

value = d.get(key, "empty")

You can use dict.get()

value = d.get(key)

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")

回答 1

别再奇怪了。它内置在语言中。

    >>>帮助(dict)

    模块内置的类字典帮助:

    类dict(object)
     | dict()->新的空字典
     | dict(mapping)->从映射对象的字典初始化的新字典
     | (键,值)对
    ...
     |  
     | 得到(...)
     | D.get(k [,d])-> D [k]如果D中有k,否则为d。d默认为无。
     |  
    ...

Wonder no more. It’s built into the language.

    >>> help(dict)

    Help on class dict in module builtins:

    class dict(object)
     |  dict() -> new empty dictionary
     |  dict(mapping) -> new dictionary initialized from a mapping object's
     |      (key, value) pairs
    ...
     |  
     |  get(...)
     |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
     |  
    ...

回答 2

采用 dict.get

如果key在字典中,则返回key的值,否则返回默认值。如果未提供default,则默认为None,因此此方法永远不会引发KeyError。

Use dict.get

Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.


回答 3

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

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

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

You should use the get() method from the dict class

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

This will result in r == None. If the key isn’t found in the dictionary, the get function returns the second argument.


回答 4

如果您想要一个更透明的解决方案,则可以继承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

If you want a more transparent solution, you can subclass dict to get this behavior:

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

回答 5

我通常在这种情况下使用defaultdict。您提供一个不带任何参数的工厂方法,并在看到新键时创建一个值。当您想在新键上返回空列表之类的功能时,它会更有用(请参见示例)。

from collections import defaultdict
d = defaultdict(lambda: None)
print d['new_key']  # prints 'None'

I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It’s more useful when you want to return something like an empty list on new keys (see the examples).

from collections import defaultdict
d = defaultdict(lambda: None)
print d['new_key']  # prints 'None'

回答 6

您可以使用dict对象的get()方法,就像其他人已经建议的那样。另外,根据您正在执行的操作,您可能可以使用如下try/except套件:

try:
   <to do something with d[key]>
except KeyError:
   <deal with it not being there>

这被认为是处理案件的非常“ Pythonic”的方法。

You could use a dict object’s get() method, as others have already suggested. Alternatively, depending on exactly what you’re doing, you might be able use a try/except suite like this:

try:
   <to do something with d[key]>
except KeyError:
   <deal with it not being there>

Which is considered to be a very “Pythonic” approach to handling the case.


回答 7

一线解决方案是:

item['key'] if 'key' in item else None

在尝试将字典值添加到新列表并想要提供默认值时,这很有用:

例如。

row = [item['key'] if 'key' in item else 'default_value']

A one line solution would be:

item['key'] if 'key' in item else None

This is useful when trying to add dictionary values to a new list and want to provide a default:

eg.

row = [item['key'] if 'key' in item else 'default_value']

回答 8

就像其他人说的那样,您可以使用get()。

但是要检查密钥,您也可以执行以下操作:

d = {}
if 'keyname' in d:

    # d['keyname'] exists
    pass

else:

    # d['keyname'] does not exist
    pass

As others have said above, you can use get().

But to check for a key, you can also do:

d = {}
if 'keyname' in d:

    # d['keyname'] exists
    pass

else:

    # d['keyname'] does not exist
    pass

回答 9

我被python2 vs python3中可能发生的事情吓了一跳。我将根据最终对python3所做的回答。我的目标很简单:检查字典格式的json响应是否给出错误。我的字典称为“令牌”,而我正在寻找的密钥是“错误”。我正在寻找键“错误”,如果不存在,则将其设置为“无”,然后检查其值为“无”,如果是,请继续执行我的代码。如果我确实拥有键“错误”,则将执行else语句。

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

I was thrown aback by what was possible in python2 vs python3. I will answer it based on what I ended up doing for python3. My objective was simple: check if a json response in dictionary format gave an error or not. My dictionary is called “token” and my key that I am looking for is “error”. I am looking for key “error” and if it was not there setting it to value of None, then checking is the value is None, if so proceed with my code. An else statement would handle if I do have the key “error”.

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

回答 10

如果可以使用False,则还可以使用hasattr内置功能:

e=dict()
hasattr(e, 'message'):
>>> False

If you can do it with False, then, there’s also the hasattr built-in funtion:

e=dict()
hasattr(e, 'message'):
>>> False