Example of item() function in Python traversing dictionary

Y2J
Release: 2017-05-17 15:12:31
Original
14483 people have browsed it

This article mainly introduces examples of using the item() method to traverse a dictionary in Python. for...in is the most commonly used method of traversing a dictionary in Python. Friends who need it can refer to it

There are several ways to traverse Python dictionary, one of which is for...in. I won't explain this. For...in can be seen almost everywhere in Python. The traversal method mentioned below is the item() method.

item()

item() method forms a tuple for each pair of key and value in the dictionary, and puts these tuples Return in list.

DEMO

Code:

The code is as follows:

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

Execution result:

It can be seen that key receives the key of the dictionary, and value receives the value of the dictionary.
But what if only one parameter is received?

The code is as follows:

person={'name':'lizhong','age':'26','city':'BeiJing','blog':' 
     for x in person.items():
         print x
Copy after login

Execution result

Only one variablereceives the value In the case of , the tuple corresponding to each pair of key and value is directly returned.

Using item() is a bit similar to foreach in php. You can traverse the key => value. If you purely use for..in, you can only get the key value of each pair of elements.

Such as code:

Code As follows:

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

Execution results:

[Related recommendations]

1. Special recommendations : "php Programmer Toolbox" V0.1 version download

2. Python free video tutorial

3. Basic introduction to Python items() method

4. Detailed explanation of the usage of items() series functions in Python

5. Introducing three methods of accessing the dictionary

6. The difference between iteriitems and items in sorted

The above is the detailed content of Example of item() function in Python traversing dictionary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template