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

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

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


当前回答

您可以使用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即可)。

其他回答

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

可以使用has_key()方法:

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

直接使用my_dict中的键,而不是my_dict.keys()中的键:

if 'key1' in my_dict:
    print("blah")
else:
    print("boo")

这将更快,因为它使用字典的O(1)哈希,而不是对关键字列表进行O(n)线性搜索。

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.

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

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

以下是方法:

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()更快。

使用Python三元运算符:

message = "blah" if 'key1' in my_dict else "booh"
print(message)