There are several ways to iterate the Python dictionary, one of which is for...in, which I do not mean that for...in is visible almost everywhere in python. The following way of traversing is the item () method.
Item ()
The item () method sets each pair of keys and value into a tuple in the dictionary and returns them in the list.
DEMO
Code:
Copy Code code as follows:
person={' name ': ' Lizhong ', ' age ': ' num ', ' City ': ' BeiJing ', ' blog ': ' Www.jb51.net '}
For Key,value in Person.items ():
print ' key= ', Key, ', value= ', value
Execution results:
The visible key receives the key,value of the dictionary and receives the value of the dictionary.
But what if there is only one parameter to receive?
Copy Code code as follows:
person={' name ': ' Lizhong ', ' age ': ' num ', ' City ': ' BeiJing ', ' blog ': ' Www.jb51.net '}
For x in Person.items ():
Print X
Execution results
When only one variable receives a value, the corresponding tuple for each pair of Key,value is returned directly.
Using item () is somewhat similar to a foreach in PHP. Can be the key => value of the way out, if the pure use for ... In, you can only get the key value for each pair of elements
such as code:
Copy Code code as follows:
person={' name ': ' Lizhong ', ' age ': ' num ', ' City ': ' BeiJing ', ' blog ': ' Www.jb51.net '}
For x in person:
Print X
Execution results: