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

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

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


当前回答

我建议改用setdefault方法。听起来它可以做你想做的一切。

>>> d = {'foo':'bar'}
>>> q = d.setdefault('foo','baz') #Do not override the existing key
>>> print q #The value takes what was originally in the dictionary
bar
>>> print d
{'foo': 'bar'}
>>> r = d.setdefault('baz',18) #baz was never in the dictionary
>>> print r #Now r has the value supplied above
18
>>> print d #The dictionary's been updated
{'foo': 'bar', 'baz': 18}

其他回答

只是给克里斯一个补充。B(最佳)答案:

d = defaultdict(int)

同样有效;原因是调用int()返回0,这是defaultdict在幕后(构造字典时)所做的,因此文档中的名称为“Factory Function”。

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

可以使用has_key()方法:

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

另一种使用布尔运算符检查键是否存在的方法:

d = {'a': 1, 'b':2}
keys = 'abcd'

for k in keys:
    x = (k in d and 'blah') or 'boo'
    print(x)

这将返回

>>> blah
>>> blah
>>> boo
>>> boo

解释

首先,您应该知道在Python中,0、None或长度为零的对象的计算结果为False。其他所有值均为True。布尔运算从左到右求值,返回的操作数不是True或False。

让我们看一个例子:

>>> 'Some string' or 1/0
'Some string'
>>>

由于“Some string”的计算结果为True,因此不会计算或的其余部分,也不会引发除零错误。

但是,如果我们切换顺序1/0,则首先求值并引发异常:

>>> 1/0 or 'Some string'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>

我们可以使用这个模式来检查是否存在密钥。

(k in d and 'blah')

if k in d:
    'blah'
else:
    False

如果键存在,这已经返回了正确的结果,但我们希望它在不存在时打印“boo”。所以,我们用“boo”表示结果

>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>

获得结果的方法有:

如果在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."

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.