在Python中称为关联数组的数据结构称为字典。字典包含键值对的集合。它提供键值对到其值的映射。
我们可以借助 Python 中的内置函数通过各种方式检查 Python 字典中是否存在该键。
本文将讨论六种不同的方法来检查 Python 字典中是否存在一个键。将有示例代码片段以及显示密钥是否存在的输出。
目录
1. Python keys() 方法:
Python keys() 方法用于获取字典元素的所有键的列表。它是一个内置函数。' in ' 运算符与此方法一起使用以检查密钥是否存在。
dictionary = {'New York': "2", 'Chicago': "4", 'Houston': "6", 'Washington':"8"}
key = 'Houston'
if key in dictionary.keys():
print( "Yes, this Key is Present" )
else:
print( "No, this Key does not exist in Dictionary" )
输出:
2. Python 'if' 和 'in' 语句:
我们可以使用条件语句' if '和 ' in ' 运算符来检查字典列表中的键。
dictionary = {'New York': "2", 'Chicago': "4", 'Houston': "6", 'Washington': "8"}
key = 'Los Angeles'
if key in dictionary.keys():
print("Yes, this Key is Present")
else:
print("No, this Key does not exist in Dictionary")
输出:
3. Python 'if not in' 语句。
除了检查字典中键的可用性之外,还有一种方法。我们可以使用' not in '语句来检查密钥是否不存在。如果键不存在,' not in ' 语句将返回 True。
dictionary = {'New York': "2", 'Chicago': "4", 'Houston': "6", 'Washington': "8"}
key = 'San Francisco'
if key not in dictionary:
print("No, this Key does not exist in the dictionary.")
else:
print("Yes, this Key is Present")
输出:
4. Python get() 函数
get()是一个 Python 内置函数。如果存在字典键,则此方法根据键值对返回与键关联的值。而当没有键时它返回 none 。
dictionary = {'New York': "2", 'Chicago': "4", 'Houston': "6", 'Washington': "8"}
if dictionary.get('Chicago')!=None:
print("Yes, this Key is Present")
else:
print("No, this Key does not exist in the dictionary.")
输出:
5. Python try/except
我们可以通过使用try/except逻辑来完成这项工作。当字典中不存在键时,我们尝试访问它,它返回一个keyError。这样,我们就可以检查字典中是否存在一个键。
def key_check(dict_test, key):
try:
value = dict_test[key]
return True
except KeyError:
return False
dictionary = {'New York': "2", 'Chicago':"4", 'Houston':"6", 'Washington':"8"}
key = 'New York'
if key_check(dictionary, key):
print("Yes, this Key is Present")
else:
print("No, this Key does not exist in the dictionary.")
输出:
结论:
不同的技术与示例一起解释,以了解如何检查一个键是否已经存在于 Python 字典中。希望这篇文章对你的开发实践有所帮助。