Python dictionary has_key() 方法用于验证字典是否由指定的键组成。如果字典中有给定的键可用,则此函数返回 True,否则返回 False。
python 字典是键和值的集合。有时需要验证字典中是否存在特定键。这是在 has_key() 方法的帮助下完成的。
注意:has_key() 方法仅在 Python 2.x 中可执行。它在 Python 3.x 中已弃用。请改用 in 运算符。
语法
以下是 Python 字典 has_key() 方法的语法 -
dict.has_key(key)
参数
- key − 这是需要在字典中搜索的 Key。
返回值
如果字典中提供了给定的键,则此方法返回布尔值 true,否则返回 false。
例如果字典中存在作为参数传递的键,则此方法将返回布尔值 True。
以下示例显示了 Python dictionary has_key() 方法的用法。在这里,创建了一个字典 'dict',其中包含键 'Name' 和 'Age'。然后,键 'Age' 作为参数传递给 has_key() 方法。
# creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
# returning the boolean value
print "Value : %s" % dict.has_key('Age')
当我们运行上述程序时,它会产生以下结果——
Value : True
例
如果在当前字典中找不到作为参数传递的键,则此方法返回 False。
在下面给出的这个例子中,我们创建的字典包含键:'Name' 和 'Age'。然后,我们试图找到字典中不存在的键 “”。
# creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
# printing the result
print "Value : %s" % dict.has_key('Sex')
在执行上述代码时,我们得到以下输出 -
Value : False
例
has_key() 在 Python 3 中已被弃用。因此,in 运算符用于检查字典中是否存在指定的键。
dict_1 = {6: "Six", 7: "Seven", 8: "Eight"}
print("The dictionary is {}".format(dict_1))
# Returns True if the key is present in the dictionary
if 7 in dict_1:
print(dict_1[7])
else:
print("{} is not present".format(7))
# Returns False if the key is not present in the dictionary
if 12 in dict_1.keys():
print(dict_1[12])
else:
print("{} is not present".format(12))
以下是上述代码的输出 -
The dictionary is {6: 'Six', 7: 'Seven', 8: 'Eight'}
Seven
12 is not present
Seven
12 is not present