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
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
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
Execution results:
[Related recommendations]
1. Special recommendations : "php Programmer Toolbox" V0.1 version download
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!