Python 字典 values() 方法



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

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

語法

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

dict.values()

引數

此方法不接受任何引數。

返回值

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

示例

以下示例顯示了 Python 字典 values() 方法的使用。首先,我們建立一個包含值“Zara”和“7”的字典“dict”。然後,我們使用 values() 方法檢索字典的所有值。

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

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

Value : dict_values(['Zara', 7])

示例

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

在以下示例中,建立了一個字典“dict1”。此字典包含值“Lion”和“Carnivora”。然後,我們在字典中新增一個專案,該專案包含鍵“Kingdom”及其對應值“Animalia”。然後,使用 values() 方法檢索字典的所有值

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

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

The values of the dictionary are:  dict_values(['Lion', 'Carnivora', 'Animalia'])

示例

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

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

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

The dictionary is:  dict_values([])

示例

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

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

以上程式碼的輸出如下:

Lion
Carnivora
Animalia
python_dictionary.htm
廣告