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

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

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


当前回答

您可以使用for循环来遍历字典,并获得要在字典中查找的键的名称。之后,检查是否存在或不使用if条件:

dic = {'first' : 12, 'second' : 123}
for each in dic:
    if each == 'second':
        print('the key exists and the corresponding value can be updated in the dictionary')

其他回答

直接使用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.

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

可以使用has_key()方法:

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

您可以使用for循环来遍历字典,并获得要在字典中查找的键的名称。之后,检查是否存在或不使用if条件:

dic = {'first' : 12, 'second' : 123}
for each in dic:
    if each == 'second':
        print('the key exists and the corresponding value can be updated in the dictionary')

您可以将代码缩短为:

if 'key1' in my_dict:
    ...

然而,这充其量只是一种外观上的改进。为什么你认为这不是最好的方法?