检查给定键是否已存在于字典中
为了了解如何做到这一点,我们首先检查我们可以在字典上调用哪些方法。
方法如下:
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() 更可靠,而且速度更快。