Python - 字典檢視物件



dict 類的 `items()`、`keys()` 和 `values()` 方法返回檢視物件。這些檢視會在其來源 字典 物件內容發生任何更改時動態重新整理。

items() 方法

items() 方法返回一個 dict_items 檢視物件。它包含一個 列表,其中包含 元組,每個元組都由相應的鍵值對組成。

語法

以下是 items() 方法的語法:

Obj = dict.items()

返回值

items() 方法返回 dict_items 物件,它是 (鍵, 值) 元組的動態檢視。

示例

在下面的示例中,我們首先使用 items() 方法獲取 dict_items 物件,並在字典物件更新時檢查它是如何動態更新的。

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
obj = numbers.items()
print ('type of obj: ', type(obj))
print (obj)
print ("update numbers dictionary")
numbers.update({50:"Fifty"})
print ("View automatically updated")
print (obj)

輸出結果如下:

type of obj: <class 'dict_items'>
dict_items([(10, 'Ten'), (20, 'Twenty'), (30, 'Thirty'), (40, 'Forty')])
update numbers dictionary
View automatically updated
dict_items([(10, 'Ten'), (20, 'Twenty'), (30, 'Thirty'), (40, 'Forty'), (50, 'Fifty')])

keys() 方法

dict 類的 keys() 方法返回 dict_keys 物件,這是一個字典中所有鍵的列表。它是一個檢視物件,因為每當對字典物件執行任何更新操作時,它都會自動更新。

語法

以下是 keys() 方法的語法:

Obj = dict.keys()

返回值

keys() 方法返回 dict_keys 物件,它是字典中鍵的檢視。

示例

在這個例子中,我們建立一個名為 "numbers" 的字典,它包含整型鍵和它們對應的字串值。然後,我們使用 keys() 方法獲取鍵的檢視物件 "obj",並檢索它的型別和內容:

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
obj = numbers.keys()
print ('type of obj: ', type(obj))
print (obj)
print ("update numbers dictionary")
numbers.update({50:"Fifty"})
print ("View automatically updated")
print (obj)

輸出結果如下:輸出

type of obj: <class 'dict_keys'>
dict_keys([10, 20, 30, 40])
update numbers dictionary
View automatically updated
dict_keys([10, 20, 30, 40, 50])

values() 方法

values() 方法返回字典中所有值的檢視。該物件是 dict_value 型別,會自動更新。

語法

以下是 values() 方法的語法:

Obj = dict.values()

返回值

values() 方法返回字典中所有值的 dict_values 檢視。

示例

在下面的示例中,我們從 "numbers" 字典中使用 values() 方法獲取值的檢視物件 "obj":

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
obj = numbers.values()
print ('type of obj: ', type(obj))
print (obj)
print ("update numbers dictionary")
numbers.update({50:"Fifty"})
print ("View automatically updated")
print (obj)

輸出結果如下:輸出

type of obj: <class 'dict_values'>
dict_values(['Ten', 'Twenty', 'Thirty', 'Forty'])
update numbers dictionary
View automatically updated
dict_values(['Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty'])
廣告