在 Python 中检查给定的键是否已存在于字典中
pythonserver side programmingprogramming更新于 2026/1/13 1:48:17
字典将键和值以对的形式存储在管道中。有时我们可能需要查找给定的键是否已存在于字典中。在本文中,我们将看到检查字典中是否存在键的各种方法。
使用 in
这是一种非常简单的方法,我们只需使用 in 运算符检查字典中是否存在键。如果字典中的键部分存在,我们将结果打印为存在,否则不存在。
示例
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("The given dictionary : ",Adict)
check_key = "Fri"
if check_key in Adict:
print(check_key,"is Present.")
else:
print(check_key, " is not Present.")
输出
运行上述代码得到以下结果 −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Fri is not Present.
使用 dict.keys
dict.keys() 方法为我们提供给定字典中存在的所有键。我们可以使用 in 运算符来找出给定键是否属于给定字典。
示例
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("The given dictionary : ",Adict)
check_key = "Wed"
if check_key in Adict.keys():
print(check_key,"is Present.")
else:
print(check_key, " is not Present.")
输出
运行上述代码得到以下结果 −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Wed is Present.
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

