我想在更新键的值之前测试字典中是否存在键。我编写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的关键字?
我想在更新键的值之前测试字典中是否存在键。我编写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的关键字?
当前回答
另一种使用布尔运算符检查键是否存在的方法:
d = {'a': 1, 'b':2}
keys = 'abcd'
for k in keys:
x = (k in d and 'blah') or 'boo'
print(x)
这将返回
>>> blah
>>> blah
>>> boo
>>> boo
解释
首先,您应该知道在Python中,0、None或长度为零的对象的计算结果为False。其他所有值均为True。布尔运算从左到右求值,返回的操作数不是True或False。
让我们看一个例子:
>>> 'Some string' or 1/0
'Some string'
>>>
由于“Some string”的计算结果为True,因此不会计算或的其余部分,也不会引发除零错误。
但是,如果我们切换顺序1/0,则首先求值并引发异常:
>>> 1/0 or 'Some string'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
我们可以使用这个模式来检查是否存在密钥。
(k in d and 'blah')
与
if k in d:
'blah'
else:
False
如果键存在,这已经返回了正确的结果,但我们希望它在不存在时打印“boo”。所以,我们用“boo”表示结果
>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>
其他回答
获得结果的方法有:
如果在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 = {'a': 1, 'b':2}
keys = 'abcd'
for k in keys:
x = (k in d and 'blah') or 'boo'
print(x)
这将返回
>>> blah
>>> blah
>>> boo
>>> boo
解释
首先,您应该知道在Python中,0、None或长度为零的对象的计算结果为False。其他所有值均为True。布尔运算从左到右求值,返回的操作数不是True或False。
让我们看一个例子:
>>> 'Some string' or 1/0
'Some string'
>>>
由于“Some string”的计算结果为True,因此不会计算或的其余部分,也不会引发除零错误。
但是,如果我们切换顺序1/0,则首先求值并引发异常:
>>> 1/0 or 'Some string'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
我们可以使用这个模式来检查是否存在密钥。
(k in d and 'blah')
与
if k in d:
'blah'
else:
False
如果键存在,这已经返回了正确的结果,但我们希望它在不存在时打印“boo”。所以,我们用“boo”表示结果
>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>
仅Python 2:(Python 2.7已经支持“in”)
可以使用has_key()方法:
if dict.has_key('xyz')==1:
# Update the value for the key
else:
pass
在字典中是否存在密钥的测试中:
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.