Python 简明教程

Python - Dictionary View Objects

dict 类的 items()keys()values() 方法返回视图对象。每当其源 dictionary 对象的内容发生任何更改时,这些视图都会动态刷新。

The items() Method

items() 方法返回一个 dict_items 视图对象。它包含 listtuples ,每个元组由各自的键值对组成。

Syntax

以下是 items() 方法的语法 −

Obj = dict.items()

Return value

items() 方法返回 dict_items 对象,它是 (key,value) 元组的动态视图。

Example

在下面的示例中,我们首先使用 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')])

The keys() Method

dict 类的 keys() 方法返回 dict_keys 对象,它是字典中定义的所有键的列表。它是一个视图对象,因为每当对字典对象执行任何更新操作时,它都会自动更新。

Syntax

以下是 keys() 方法的语法 −

Obj = dict.keys()

Return value

keys() 方法返回 dict_keys 对象,它是字典中键的视图。

Example

在这个示例中,我们创建了一个名为“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)

它将生成以下 output

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])

The values() Method

values() 方法返回字典中所有值的视图。该对象是 dict_value 类型的,它会自动更新。

Syntax

以下是 values() 方法的语法 −

Obj = dict.values()

Return value

values() 方法返回一个 dict_values 视图,该视图包含字典中存在的全部值。

Example

在下面的示例中,我们从“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)

它将生成以下 output

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'])