Python Dictionary items() 函数用法
2023-09-17 22:23:30
dict.items()
返回一个dictionary view object,该以键值对列表的形式提供字典元素的动态视图。此视图对象在字典更改时更改。
语法:
dict.items()
参数:
无参数。
返回值:
返回一个视图对象dict_items
,该对象显示字典的键值对的列表。
下面的示例演示 dict.items()
方法。
romanNums = {'I':1,'II':2,'III':3,'IV':4}
dictview = romanNums.items()
print(dictview)
输出:
dict_items([('I', 1), ('II', 2), ('III', 3), ('IV', 4)])
下面的示例演示更新字典时视图对象如何更改。
romanNums = {'I':1,'II':2,'III':3,'IV':4}
dictview = romanNums.items()
print("Dictionary View Object: ", dictview)
romanNums['V'] = 5
print("Dictionary View Object after adding new element: ", dictview)
输出:
Dictionary View Object: dict_items([('I', 1), ('II', 2), ('III', 3), ('IV', 4)])
Dictionary View Object after adding new element: dict_items([('I', 1), ('II', 2), ('III', 3), ('IV', 4), ('V', 5)])