Home  >  Article  >  Backend Development  >  Python中使用item()方法遍历字典的例子

Python中使用item()方法遍历字典的例子

WBOY
WBOYOriginal
2016-06-16 08:42:281271browse

Python字典的遍历方法有好几种,其中一种是for...in,这个我就不说明,在Python了几乎随处都可见for...in。下面说的这种遍历方式是item()方法。

item()

item()方法把字典中每对key和value组成一个元组,并把这些元组放在列表中返回。

DEMO

代码:

复制代码 代码如下:

person={'name':'lizhong','age':'26','city':'BeiJing','blog':'www.jb51.net'}
 
for key,value in person.items():
    print 'key=',key,',value=',value

执行结果:

可见key接收了字典的key,value接收了字典的value值。
但如果只有一个参数接收呢?

复制代码 代码如下:

person={'name':'lizhong','age':'26','city':'BeiJing','blog':'www.jb51.net'}
    
for x in person.items():
    print x

执行结果

只有一个变量接收值的情况下,直接返回的是每一对key,value对应的元组。

使用item()就有点类似于php里的foreach类似。都能把键=>值的方式遍历出来,如果纯使用for..in则只能取得每一对元素的key值

如代码:

复制代码 代码如下:

person={'name':'lizhong','age':'26','city':'BeiJing','blog':'www.jb51.net'}
    
for x in person:
    print x

执行结果:

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn