python items()方法,与for循环结合使用

items()方法

python的字典items()方法,可以返回一个dict_items对象,其中有一部分是由元素为字典的键key和值value组成的元组的列表,鄙人在python的一些开发经验当中,比较经常将字典的Items()方法同python的for循环配合使用,以同时对字典的键和值进行遍历。


items()语法及参数

dict.items()

items()方法不接收参数,否则python会抛出TypeError。


items()返回值

dict_items类实例对象。


items()与for循环结合实例代码

>>> d = {'web': 'x1y1z1.com', 'name': '笨鸟工具'}
>>> d.items()
dict_items([('web', 'x1y1z1.com'), ('name', '笨鸟工具')])
>>> type(d.items())
<class 'dict_items'>
>>> d.items(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: items() takes no arguments (1 given)
>>> for k, v in d.items():
...     print('key:%s;value:%s' %(k,v))
... 
key:web;value:x1y1z1.com
key:name;value:笨鸟工具
>>> for k in d:
...     print(k)
... 
web
name

实例代码解析

1、将字典对象调用items()的返回值作为参数传递给type()方法,返回值为<class 'dict_items'>;2、如上代码,当直接对字典d进行循环迭代,会发现取到的值是键key;3、尝试给items()方法传递一个参数时,python会抛出TypeError,并提示:items() takes no arguments (1 given),即items()方法不需要参数。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.