Python typically uses the for...in traversal dictionary, which is used in this article to traverse the dictionary using the item () method.
Item ()
The item () method consists of a tuple of each pair of keys and value in the dictionary, and the tuples are placed back in the list.
DEMO
The code is as follows:
#!/usr/bin/env python
#-*-Coding:utf-8-*-
Dict = {"Name": "Zhangsan", "Age": "$", "City": "Shanghai", "blog": "Http://www.jb51.net"}
For Key,value in Dict.items ():
print ' key= ', Key, ' value= ', value
Execution Result:
650) this.width=650; "title=" Untitled. jpg "src=" http://s3.51cto.com/wyfs02/M02/53/90/ Wkiom1rq-qrtuuibaabu5cybonq424.jpg "alt=" Wkiom1rq-qrtuuibaabu5cybonq424.jpg "/>
Visible key receives the dictionary's key,value to receive the dictionary value value.
But what if only one parameter is received?
The code is as follows:
person={' name ': ' Lizhong ', ' age ': ' + ', ' City ': ' Beijing ', ' blog ': ' Www.jb51.net '}
For x in Person.items ():
Print X
Execution results
650) this.width=650; "title=" Untitled 1.png "src=" http://s3.51cto.com/wyfs02/M00/53/8E/wKioL1Rq_ Ddhhdo0aabtekedhfe473.jpg "alt=" Wkiol1rq_ddhhdo0aabtekedhfe473.jpg "/>
When only one variable receives a value, the tuple that corresponds to each pair of Key,value is returned directly.
Using the item () is a bit similar to a foreach in PHP. Can be a key to the value of the way to traverse out, if pure use for. In can only get the key value for each pair of elements
The code is as follows:
person={' name ': ' Lizhong ', ' age ': ' + ', ' City ': ' Beijing ', ' blog ': ' Www.jb51.net '}
For x in person:
Print X
Execution Result:
650) this.width=650; "title=" Untitled 2.png "src=" http://s3.51cto.com/wyfs02/M02/53/90/ Wkiom1rq-6yg2m9jaaa8vpbnsf8240.jpg "alt=" Wkiom1rq-6yg2m9jaaa8vpbnsf8240.jpg "/>
Use item () to traverse a dictionary in Python