Python 字典 has_key() 方法



Python 字典 has_key() 方法用於驗證字典是否包含指定的鍵。如果給定的在字典中存在,則此函式返回 True,否則返回 False。

Python 字典是鍵和值的集合。有時需要驗證某個特定的鍵是否存在於字典中。這可以透過 has_key() 方法來實現。

注意:has_key() 方法僅在 Python 2.x 中可用。在 Python 3.x 中已棄用。請改用in 運算子

語法

以下是Python 字典 has_key() 方法的語法:

dict.has_key(key)

引數

  • key - 需要在字典中搜索的鍵。

返回值

如果給定的鍵在字典中存在,則此方法返回布林值 True,否則返回 False。

示例

如果作為引數傳遞的鍵存在於字典中,則此方法返回布林值 True。

以下示例演示了 Python 字典 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'。然後,我們嘗試查詢字典中不存在的鍵 "Sex"。

# creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
# printing the result
print "Value : %s" %  dict.has_key('Sex')

執行上述程式碼時,我們得到以下輸出:

Value : False

示例

Python 3 中已棄用 has_key() 方法。因此,使用 **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
python_dictionary.htm
廣告