Python 字典 keys() 方法



Python 字典 keys() 方法用於檢索字典中所有鍵的列表。

在 Python 中,字典是一組鍵值對。這些也被稱為“對映”,因為它們“對映”或“關聯”鍵物件與值物件。keys() 方法返回的檢視物件中包含與 Python 字典相關的所有鍵的列表。

語法

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

dict.keys()

引數

此方法不接受任何引數。

返回值

此方法返回字典中所有可用鍵的列表。

示例

以下示例顯示了 Python 字典 keys() 方法的使用。首先,我們建立一個包含鍵:'Name' 和 'Age' 的字典 'dict'。然後,我們使用 keys() 方法檢索字典的所有鍵。

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

當我們執行上述程式時,它會產生以下結果:

Value : dict_keys(['Name', 'Age'])

示例

當在字典中新增專案時,檢視物件也會更新。

在以下示例中,建立了一個字典 'dict1'。此字典包含鍵:'Animal' 和 'Order'。然後,我們在字典中追加一個專案,該專案包含鍵 'Kingdom' 及其對應值 'Animalia'。然後使用 keys() 方法檢索字典的所有鍵

# creating the dictionary
dict_1 = {'Animal': 'Lion', 'Order': 'Carnivora'}
res = dict_1.keys()
# Appending an item in the dictionary
dict_1['Kingdom'] = 'Animalia'
# Printing the result
print ("The keys of the dictionary are: ", res)

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

The keys of the dictionary are:  dict_keys(['Animal', 'Order', 'Kingdom'])

示例

如果在空字典上呼叫此方法,keys() 方法不會引發任何錯誤。它返回一個空字典。

# Creating an empty dictionary  
Animal = {} 
# Invoking the method  
res = Animal.keys()  
# Printing the result  
print('The dictionary is: ', res)  

以下是上述程式碼的輸出:

The dictionary is:  dict_keys([])

示例

在以下示例中,我們使用 for 迴圈遍歷字典的鍵。然後返回結果

# Creating a dictionary
dict_1 = {'Animal': 'Lion', 'Order': 'Carnivora', 'Kingdom':'Animalia'}
# Iterating through the keys of the dictionary
for res in dict_1.keys():
    print(res)

上述程式碼的輸出如下:

Animal
Order
Kingdom
python_dictionary.htm
廣告