Example of using the item () method to traverse the dictionary in Python

Source: Internet
Author: User
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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.