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

Source: Internet
Author: User
There are several ways to traverse a Python dictionary, one of which is for...in, which I do not specify, which is visible in python almost everywhere for...in. The following way of traversal is 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

Code:
Copy the Code code as follows:


person={' name ': ' Lizhong ', ' age ': ' + ', ' City ': ' Beijing ', ' blog ': ' Www.jb51.net '}

For Key,value in Person.items ():
print ' key= ', Key, ', value= ', value


Execution Result:

Visible key receives the dictionary's key,value to receive the dictionary value value.
But what if only one parameter is received?
Copy the Code code as follows:


person={' name ': ' Lizhong ', ' age ': ' + ', ' City ': ' Beijing ', ' blog ': ' Www.jb51.net '}

For x in Person.items ():
Print X


Execution results

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

such as code:
Copy the Code code as follows:


person={' name ': ' Lizhong ', ' age ': ' + ', ' 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.