Python 如何检查字典中是否存在某个键
字典以无序且可变的方式维护唯一键到值的映射关系。在Python中,字典是一种特殊的数据结构,使用键值对存储数据值。字典用花括号表示,并且包含键和值。
从Python 3.7开始,字典现在是有序的。Python 3.6及之前的字典不排序。
示例
在下面的示例中,companyname和tagline是键,Tutorialspoint和simplyeasylearning分别是值。
thisdict = {
"companyname": "Tutorialspoint",
"tagline" : "simplyeasylearning",
}
print(thisdict)
输出
上述代码产生以下结果。
{'companyname': 'Tutorialspoint', 'tagline': 'simplyeasylearning'}
在本文中,我们检查字典中是否存在某个键。为此,有许多方法,并且下面讨论了每一种方法。
使用in操作符
我们使用’in’操作符来检查字典中是否存在该键。
‘in’操作符在给定的字典中存在该键时返回“True”,在字典中不存在该键时返回“False”。
示例1
以下示例使用in操作符来检查给定字典中是否存在特定键。
this_dict = { "companyname" : "Tutorialspoint", "tagline" : "simplyeasylearning" , 'location': 'India'}
if "companyname" in this_dict:
print("Exists")
else:
print("Does not exist")
if "name" in this_dict:
print("Exists")
else:
print("Does not exist")
输出
下面显示的是产生的输出。
Exists
Does not exist
示例2
以下是另一个示例−
my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}
print('name' in my_dict)
print('foo' in my_dict)
输出
这将产生输出:
True
False
使用get()方法
在该方法中,我们使用get()方法来判断字典中是否存在该键。get()方法返回具有指定键的项的值。
语法
这是Python中get()方法的语法。
dict.get(key,value)
在此处:
- key – 您要检索值的对象的键名。
- value – 如果给定的键不存在,则返回此值。 默认值为None。
示例1
此示例显示了Python中可用的get()方法的用法。
this_dict = { "companyname" : "Tutorialspoint", "tagline" : "simplyeasylearning" , 'location': 'India'}
if this_dict.get("tagline") is not None:
print("Exists")
else:
print("Does not exist")
if this_dict.get("address") is not None:
print("Exists")
else:
print("Does not exist")
输出
当上述代码运行时产生的输出如下所示。
Exists
Does not exist