This article mainly introduces the example of using the item () method to traverse the dictionary in Python,... in is the most commonly used method to traverse the dictionary in Python. you can refer to several methods to traverse the dictionary in Python, one of which is... in, I don't know. it's almost everywhere in Python.... in. The traversal method described below is the item () method.
Item ()
The item () method combines every pair of key and value in the dictionary into a tuple, and puts these tuples in the list to return.
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 the key receives the dictionary key, and the value receives the dictionary value.
But what if only one parameter is received?
The code is as follows:
Person = {'name': 'lizhong ', 'age': '26', 'City': 'Beijing', 'blog': 'www .jb51.net '}
For x in person. items ():
Print x
Execution result
If only one variable receives a value, each pair of key and value tuples are directly returned.
Using item () is similar to foreach in php. The key => value can be traversed. if you only use for... in, you can only obtain the key value of each pair of elements.
Such as code:
The code is as follows:
Person = {'name': 'lizhong ', 'age': '26', 'City': 'Beijing', 'blog': 'www .jb51.net '}
For x in person:
Print x
Execution result: