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

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

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


当前回答

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

d = defaultdict(int)

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

其他回答

我建议改用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}

Python中的字典有一个get('key',默认)方法。因此,您可以设置一个默认值,以防没有任何键。

values = {...}
myValue = values.get('Key', None)

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

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.

有关已接受答案的建议方法(1000万个循环)执行速度的其他信息:

mydict中的“key”已用时间1.07秒mydict.get('key')运行时间1.84秒mydefaultdict['key']已用时间1.07秒

因此,建议对get使用in或defaultdict。