学习Python 的dict.items()方法

250 阅读1分钟

摘要字典 数据结构有许多有用的方法,其中一个方法是dict.items() 方法。为了能够迭代 和显示字典中的元素,Python字典items() 方法做了这个功能。dict.items() 方法以键值图元列表的形式显示字典所占的元素。

定义dict.items() 方法输出一个 dictionary 的 (key, value)元组 对的列表。

dict.items()的语法

方法声明:

dict.items()

参数dict.items() 方法不输入任何参数。

返回值: dict.items() 方法输出一个视图对象类型,显示一个字典的(key, value)元组对的列表 ,其形式为。

[(key_1, value), (key_2, value), ..., (key_nth, value)]

Grocery Items 例子,显示字典状态改变时的结果。

# Declare a dictionary of grocery items
grocery_items = {'bread': '$5.00',
                 'melon': '$2.99',
                 'eggs': '$6.00'}


# Print grocery_items as tuples
print(grocery_items.items())


# Show if dictionary changes propagate to items() view
current_groceries = grocery_items.items()
print('original groceries: ', current_groceries)
del[grocery_items['melon']]
print('updated groceries: ', current_groceries)

输出:

dict_items([('bread', '$5.00'), ('melon', '$2.99'), ('eggs', '$6.00')])
original groceries:  dict_items([('bread', '$5.00'), ('melon', '$2.99'), ('eggs', '$6.00')])
updated groceries:  dict_items([('bread', '$5.00'), ('eggs', '$6.00')])

结果显示,current_groceries 字典是指原来的grocery_items 字典。因此,从原来的grocery_items 中删除项目也会影响到current_groceries 字典被调用的结果。