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

Source: Internet
Author: User
Tags in python

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:

Related Article

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.