我想在更新键的值之前测试字典中是否存在键。我编写了以下代码:

if 'key1' in dict.keys():
  print "blah"
else:
  print "boo"

我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的关键字?


当前回答

使用EAFP(请求宽恕比允许更容易):

try:
   blah = dict["mykey"]
   # key exists in dict
except KeyError:
   # key doesn't exist in dict

请参阅其他堆栈溢出帖子:

在Python中使用“try”与“if”检查Python中是否存在成员

其他回答

您可以使用in关键字测试字典中是否存在关键字:

d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False

在对字典中的键进行变异之前,检查其是否存在的一个常见用法是默认初始化该值(例如,如果您的值是列表,并且您希望确保在插入键的第一个值时有一个空列表可以附加到该空列表中)。在这种情况下,您可能会发现collections.defaultdict()类型很有趣。

在旧代码中,您可能还会发现has_key()的一些用法,这是一种不推荐使用的检查字典中是否存在键的方法(只需在dict_name中使用key_name即可)。

在字典中是否存在密钥的测试中:

d = {"key1": 10, "key2": 23}

if "key1" in d:
    print("this will execute")

if "nonexistent key" in d:
    print("this will not")

当键不存在时,使用dict.get()提供默认值:

d = {}

for i in range(10):
    d[i] = d.get(i, 0) + 1

要为每个键提供默认值,请对每个赋值使用dict.setdefault():

d = {}

for i in range(10):
    d[i] = d.setdefault(i, 0) + 1

或使用集合模块中的defaultdict:

from collections import defaultdict

d = defaultdict(int)

for i in range(10):
    d[i] += 1

Python字典具有名为__contains__的方法。如果字典具有键,则此方法将返回True,否则返回False。

>>> temp = {}

>>> help(temp.__contains__)

Help on built-in function __contains__:

__contains__(key, /) method of builtins.dict instance
    True if D has a key k, else False.

仅Python 2:(Python 2.7已经支持“in”)

可以使用has_key()方法:

if dict.has_key('xyz')==1:
    # Update the value for the key
else:
    pass

获得结果的方法有:

如果在Python 3中删除了your_dict.has_key(key)如果输入您的目录try/except块

哪个更好取决于三件事:

字典“通常有键”还是“通常没有键”。你打算使用if…else…elseif…else这样的条件吗?字典有多大?

阅读更多:http://paltman.com/try-except-performance-in-python-a-simple-test/

使用try/block而不是“in”或“if”:

try:
    my_dict_of_items[key_i_want_to_check]
except KeyError:
    # Do the operation you wanted to do for "key not present in dict".
else:
    # Do the operation you wanted to do with "key present in dict."