Python - 字典 has_key()

pythonserver side programmingprogramming

使用 Python 字典时,我们会遇到一种情况,即找出字典中是否存在给定的键。由于字典是无序列表,我们无法使用元素的位置来查找值。因此,Python 标准库为我们提供了一个名为 has_key() 的方法,它可以帮助我们找到字典中键的存在。此方法仅在 Python 2.x 中可用,在 Python 3.x 中不可用

语法

以下是 has_key() 方法的语法。

dict.has_key(KeyVal)
其中 KeyVal 是要搜索的键的值。
结果返回为 True 或 False。

使用数字键

如果我们使用数字作为键,我们可以在 has_key() 中直接使用数字值。

示例

Dict= { 1: 'python', 2: 'programming', 3: 'language' }
print("Given Dictionary : ")
print(Dict)
#has_key()
print(Dict.has_key(1))
print(Dict.has_key(2))
print(Dict.has_key('python'))

运行上述代码得到以下结果 −

Given Dictionary :
{1: 'python', 2: 'programming', 3: 'language'}
True
True
False

使用字符串作为键

如果我们使用字符串作为键,我们可以在 has_key() 中直接使用带引号的字符串值。

示例

Dict= { 'A': 'Work', 'B': 'From', 'C': 'Home' }
print("Given Dictionary : ")
print(Dict)
#has_key()
print(Dict.has_key('From'))
print(Dict.has_key('A'))

运行上述代码得到以下结果 −

Given Dictionary :
{'A': 'Work', 'C': 'Home', 'B': 'From'}
False
True

相关文章