检查给定的键在Python的字典中是否已经存在
管道中的字典容器将键和值成对存储。有时我们可能需要查找字典中是否已经存在给定的键。在本文中,我们将介绍检查字典中是否存在键的各种方法。
内
这是一种非常简单的方法,我们只需要使用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,"存在。")
else:
print(check_key, " 不存在。")输出结果
运行上面的代码给我们以下结果-
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Fri 不存在。使用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,"存在。")
else:
print(check_key, " 不存在。")输出结果
运行上面的代码给我们以下结果-
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Wed 存在。热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿