Python字典的View Objects怎么用?

文章导读
Previous Quiz Next dict 类的 items()、keys() 和 values() 方法返回 view objects。这些视图会在源 dictionary 对象内容发生任何更改时动态刷新。
📋 目录
  1. A items() 方法
  2. B keys() 方法
  3. C values() 方法
A A

Python - Dictionary View Objects



Previous
Quiz
Next

dict 类的 items()、keys() 和 values() 方法返回 view objects。这些视图会在源 dictionary 对象内容发生任何更改时动态刷新。

items() 方法

items() 方法返回一个 dict_items view object。它包含一个元组列表,每个元组由相应的 key、value 对组成。

语法

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

Obj = dict.items()

返回值

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

示例

在以下示例中,我们首先使用 items() 方法获取 dict_items 对象,并检查当 dictionary 对象更新时它如何动态更新。

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 对象,它是 dictionary 中定义的所有 key 的列表。它是一个 view object,当对 dictionary 对象执行任何更新操作时,它会自动更新。

语法

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

Obj = dict.keys()

返回值

keys() 方法返回 dict_keys 对象,它是 dictionary 中 key 的视图。

示例

在这个示例中,我们创建了一个名为 "numbers" 的 dictionary,使用整数 key 及其对应的字符串值。然后,我们使用 keys() 方法获取 key 的 view object "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() 方法返回 dictionary 中所有值的视图。该对象是 dict_values 类型,会自动更新。

语法

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

Obj = dict.values()

返回值

values() 方法返回 dictionary 中所有值的 dict_values 视图。

示例

在下面的示例中,我们从 "numbers" dictionary 使用 values() 方法获取值的 view object "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'])