5. Python items()

发布时间:2023-12-08

Python items()

更新:2022-07-24 12:58 python 中的 items() 函数返回一个 view 对象,该对象显示字典中所有元素的键值(元组)对。

dictionary.items()

items()参数:

items() 方法不接受任何参数。

items()返回值

如果我们对字典进行任何更改,它也会反映视图对象。如果字典是空的,结果将是一个空视图。

投入 返回值
字典 查看对象

Python 中 items() 方法的示例

示例 1: 如何使用 items() 获取字典的所有项?

# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
print(fruits.items())

输出:

dict_items([('mango', 5), ('banana', 4), ('strawberry', 3)])

示例 2: 修改字典时 items() 的工作?

# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
itemlist = fruits.items()
print('Original list:', itemlist)
# delete an item from dictionary
del[fruits['mango']]
print('Updated list:', itemlist)

输出:

Original list: dict_items([('mango', 5), ('banana', 4), ('strawberry', 3)])
Updated list: dict_items([('banana', 4), ('strawberry', 3)])