Python item()方法返回字典的新视图。该视图是键值元组的集合。此方法不带任何参数,如果字典为空,则返回空视图。示例和语法在下面给出。
items()
它返回字典的视图。
这是一个简单的示例,它返回字典中存在的所有项目。
# Python dictionary items() Method # Creating a dictionary student = {'name':'rohan', 'course':'B.Tech', 'email':'rohan@abc.com'} # 函数调用 items = student.items() # 显示结果 print(items)
输出:
dict_items([('name', 'rohan'), ('course', 'B.Tech'), ('email', 'rohan@abc.com')])
如果字典已经为空,则此方法不会引发任何错误。请参见下面的示例。
# Python dictionary items() Method # Creating a dictionary student = {} # dictionary is empty # 函数调用 items = student.items() # 显示结果 print(items)
输出:
dict_items([])
除了items()方法,无涯教程还可以使用其他自定义方法来获取字典元素。请参见下面的示例。
# Python dictionary items() Method # Creating a dictionary student = {'name':'rohan', 'course':'B.Tech', 'email':'rohan@abc.com'} # Iterating using key and value for st in student: print("(",st, ":", student[st], end="), ") # 函数调用 items = student.items() # 显示结果 print("\n", items)
输出:
( name : rohan), ( course : B.Tech), ( email : rohan@abc.com), dict_items([('name', 'rohan'), ('course', 'B.Tech'), ('email', 'rohan@abc.com')])
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)