Python3 中的 dict.items()函数

首页 / Python3入门教程 / Python3 中的 dict.items()函数

Python item()方法返回字典的新视图。该视图是键值元组的集合。此方法不带任何参数,如果字典为空,则返回空视图。示例和语法在下面给出。

dict.items - 语法

dict.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')])

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

TensorFlow快速入门与实战 -〔彭靖田〕

重学前端 -〔程劭非(winter)〕

ZooKeeper实战与源码剖析 -〔么敬国〕

WebAssembly入门课 -〔于航〕

小马哥讲Spring AOP编程思想 -〔小马哥〕

手把手教你玩音乐 -〔邓柯〕

超级访谈:对话张雪峰 -〔张雪峰〕

Go进阶 · 分布式爬虫实战 -〔郑建勋〕

手把手带你搭建推荐系统 -〔黄鸿波〕

好记忆不如烂笔头。留下您的足迹吧 :)