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

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

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


当前回答

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

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

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

其他回答

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

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

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

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

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 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三元运算符:

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

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