检查给定的键是否已存在于字典中
- 2024-11-25 08:49:00
- admin 原创
- 161
问题描述:
我想在更新键的值之前测试一下字典中是否存在该键。我写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方法。有没有更好的方法来测试字典中的键?
解决方案 1:
in
测试 a 中键的存在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(100):
key = i % 10
d[key] = d.get(key, 0) + 1
要为每个键提供默认值,可以dict.setdefault()
在每个分配中使用:
d = {}
for i in range(100):
d[i % 10] = d.setdefault(i % 10, 0) + 1
...或者更好,defaultdict
从collections
模块中使用:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
解决方案 2:
直接使用key in my_dict
而不是key in my_dict.keys()
:
if 'key1' in my_dict:
print("blah")
else:
print("boo")
这将更快,因为它使用字典的 O(1)散列,而不是在键列表上进行 O(n)线性搜索。
解决方案 3:
您可以使用in关键字测试字典中是否存在某个键:
d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False
在改变字典中的键之前检查其是否存在的常见用途是默认初始化该值(例如,如果您的值是列表,并且您想确保在插入键的第一个值时有一个可以附加的空列表)。在这种情况下,您可能会发现类型collections.defaultdict()
很有趣。
在较旧的代码中,您可能还会发现一些用途has_key()
,这是一种用于检查字典中键是否存在的弃用方法(只需使用key_name in dict_name
, 即可)。
解决方案 4:
您可以将代码缩短为:
if 'key1' in my_dict:
...
然而,这最多只是表面的改善。你为什么认为这不是最好的方法?
解决方案 5:
有关已接受答案的建议方法(1000 万个循环)的速度执行的更多信息:
'key' in mydict
耗时 1.07 秒mydict.get('key')
耗时 1.84 秒mydefaultdict['key']
耗时 1.07 秒
因此,建议不要使用in
或。defaultdict
`get`
解决方案 6:
我建议改用该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}
解决方案 7:
Python 中的字典有一个get('key', default)
方法。因此,如果没有任何键,您可以设置一个默认值。
values = {...}
myValue = values.get('Key', None)
解决方案 8:
使用Python 三元运算符:
message = "blah" if 'key1' in my_dict else "booh"
print(message)
解决方案 9:
使用 EAFP(请求原谅比请求许可更容易):
try:
blah = dict["mykey"]
# key exists in dict
except KeyError:
# key doesn't exist in dict
请参阅其他 Stack Overflow 帖子:
在 Python 中使用 'try' 与 'if'
在 Python 中检查成员是否存在
解决方案 10:
检查给定的键是否已存在于字典中
为了了解如何做到这一点,我们首先检查可以在字典中调用哪些方法。
方法如下:
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
:
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
我们使用它来获取键是否存在的信息。但是如果我们创建一个只有一个的字典,请考虑这一点key:None
:
d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None
导致该get()
方法在某些值可能不准确的情况下不可靠None
。
这个故事应该有一个更美好的结局。如果我们使用in
比较器:
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
比较运算符不仅更可靠,而且比更快get()
。
解决方案 11:
您可以通过以下方式获取结果:
if your_dict.has_key(key)在 Python 3 中被删除
如果在 your_dict 中键入
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."
解决方案 12:
仅限 Python 2:(Python 2.7 已经支持 in
)
您可以使用has_key()
以下方法:
if dict.has_key('xyz')==1:
# Update the value for the key
else:
pass
解决方案 13:
仅供参考,补充一下Chris。B 的(最佳)答案:
d = defaultdict(int)
同样有效;原因是调用int()
返回0
的是defaultdict
幕后操作(构造字典时),因此文档中称为“工厂函数”。
解决方案 14:
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.
解决方案 15:
使用布尔运算符检查键是否存在的另一种方法:
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
,因此不对其余部分or
进行计算,也不会引发除以零的错误。
但是如果我们切换顺序,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”。因此,我们取结果并将or
其与'boo'
>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>
解决方案 16:
您可以使用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')