Python-字典has_key()
使用python字典时,我们面临着一种情况,即找出字典中是否存在给定键。由于字典是元素的无序列表,因此无法使用元素的位置来找到值。因此,python标准库为我们提供了一种称为has_key()的方法,该方法可以帮助我们在字典中查找键的存在。此方法仅在python2.x中可用,而在python3.x中不可用
语法
以下是has_key()方法的语法。
dict.has_key(KeyVal) Where KeyVal is the value of the key to be searched. The result is returned as True or 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