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

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

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


当前回答

检查字典中是否已存在给定的键

为了了解如何做到这一点,我们首先检查可以调用字典的方法。

以下是方法:

d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

Python Dictionary clear()        Removes all Items
Python Dictionary copy()         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys()     Creates dictionary from given sequence
Python Dictionary get()          Returns Value of The Key
Python Dictionary items()        Returns view of dictionary (key, value) pair
Python Dictionary keys()         Returns View Object of All Keys
Python Dictionary pop()          Removes and returns element having given key
Python Dictionary popitem()      Returns & Removes Element From Dictionary
Python Dictionary setdefault()   Inserts Key With a Value if Key is not Present
Python Dictionary update()       Updates the Dictionary
Python Dictionary values()       Returns view of all values in dictionary

检查密钥是否已经存在的残酷方法可能是get()方法:

d.get("key")

另外两个有趣的方法items()和keys()听起来工作量太大。因此,让我们来看看get()是否是适合我们的方法

d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

打印显示我们没有的密钥将返回None:

print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1

如果密钥存在或不存在,我们将使用它来获取信息。但如果我们使用一个键创建一个dict:None:

d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None

在某些值可能为None的情况下,引导get()方法是不可靠的。

这个故事应该有一个更美好的结局。如果我们使用内部比较器:

print('key' in d) #True
print('key2' in d) #False

我们得到了正确的结果。

我们可以检查Python字节码:

import dis
dis.dis("'key' in d")
#   1           0 LOAD_CONST               0 ('key')
#               2 LOAD_NAME                0 (d)
#               4 COMPARE_OP               6 (in)
#               6 RETURN_VALUE

dis.dis("d.get('key2')")
#   1           0 LOAD_NAME                0 (d)
#               2 LOAD_METHOD              1 (get)
#               4 LOAD_CONST               0 ('key2')
#               6 CALL_METHOD              1
#               8 RETURN_VALUE

这表明,in compare运算符不仅更可靠,而且比get()更快。

其他回答

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

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

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

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

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

获得结果的方法有:

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

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

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

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

d = defaultdict(int)

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