python是否存在键_检查给定的键在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 存在。


版权声明:本文为weixin_34234442原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。