管道中的字典容器将键和值成对存储。有时我们可能需要查找字典中是否已经存在给定的键。在本文中,我们将介绍检查字典中是否存在键的各种方法。
内
这是一种非常简单的方法,我们只需要使用in运算符检查字典中键的存在。如果字典的键部分,我们将结果打印为当前,否则不存在。
示例Adict={'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("Thegivendictionary:",Adict)
check_key="Fri"
ifcheck_keyinAdict:
print(check_key,"存在。")
else:
print(check_key,"不存在。")
输出结果
运行上面的代码给我们以下结果-Thegivendictionary:{'Thu':9,'Wed':6,'Mon':3,'Tue':5}
Fri不存在。
使用dict.keys
dict.keys()方法为我们提供给定词典中存在的所有键。我们可以使用in运算符来确定给定键是否属于给定字典。
示例Adict={'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("Thegivendictionary:",Adict)
check_key="Wed"
ifcheck_keyinAdict.keys():
print(check_key,"存在。")
else:
print(check_key,"不存在。")
输出结果
运行上面的代码给我们以下结果-Thegivendictionary:{'Thu':9,'Wed':6,'Mon':3,'Tue':5}
Wed存在。
如果觉得《python是否存在键_检查给定的键在Python的字典中是否已经存在》对你有帮助,请点赞、收藏,并留下你的观点哦!