Python字典 items() 方法
Python中的Dictionary是数据值的无序集合,用于像 map 一样存储数据值,与其他仅保存单个值作为元素的 Data Types 不同,Dictionary 保存 key : value 对。
在Python Dictionary 中, items()方法用于返回包含所有字典键和值的列表。
Syntax: dictionary.items()
Parameters: This method takes no parameters.
Returns: A view object that displays a list of a given dictionary’s (key, value) tuple pair.
示例 #1:
Python3
# Python program to show working
# of items() method in Dictionary
# Dictionary with three items
Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' }
print("Dictionary items:")
# Printing all the items of the Dictionary
print(Dictionary1.items())
Python3
# Python program to show working
# of items() method in Dictionary
# Dictionary with three items
Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' }
print("Original Dictionary items:")
items = Dictionary1.items()
# Printing all the items of the Dictionary
print(items)
# Delete an item from dictionary
del[Dictionary1['C']]
print('Updated Dictionary:')
print(items)
输出:
Dictionary items:
dict_items([('A', 'Geeks'), ('B', 4), ('C', 'Geeks')])
列表中这些项目的顺序可能并不总是相同。示例 #2:在修改 Dictionary 后显示 items() 的工作。
Python3
# Python program to show working
# of items() method in Dictionary
# Dictionary with three items
Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' }
print("Original Dictionary items:")
items = Dictionary1.items()
# Printing all the items of the Dictionary
print(items)
# Delete an item from dictionary
del[Dictionary1['C']]
print('Updated Dictionary:')
print(items)
输出:
Original Dictionary items:
dict_items([('A', 'Geeks'), ('C', 'Geeks'), ('B', 4)])
Updated Dictionary:
dict_items([('A', 'Geeks'), ('B', 4)])
如果 Dictionary 随时更新,则更改会自动反映在视图对象中。