Use item () to traverse a dictionary in Python

Source: Internet
Author: User

Python typically uses the for...in traversal dictionary, which is used in this article to traverse the dictionary using 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

The code is as follows:

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Dict = {"Name": "Zhangsan", "Age": "$", "City": "Shanghai", "blog": "Http://www.jb51.net"}
For Key,value in Dict.items ():
print ' key= ', Key, ' value= ', value


Execution Result:

650) this.width=650; "title=" Untitled. jpg "src=" http://s3.51cto.com/wyfs02/M02/53/90/ Wkiom1rq-qrtuuibaabu5cybonq424.jpg "alt=" Wkiom1rq-qrtuuibaabu5cybonq424.jpg "/>


Visible key receives the dictionary's key,value to receive the dictionary value value.
But what if only one parameter is received?

The code is as follows:


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

For x in Person.items ():
Print X


Execution results

650) this.width=650; "title=" Untitled 1.png "src=" http://s3.51cto.com/wyfs02/M00/53/8E/wKioL1Rq_ Ddhhdo0aabtekedhfe473.jpg "alt=" Wkiol1rq_ddhhdo0aabtekedhfe473.jpg "/>


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

The code is as follows:


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

For x in person:
Print X


Execution Result:

650) this.width=650; "title=" Untitled 2.png "src=" http://s3.51cto.com/wyfs02/M02/53/90/ Wkiom1rq-6yg2m9jaaa8vpbnsf8240.jpg "alt=" Wkiom1rq-6yg2m9jaaa8vpbnsf8240.jpg "/>


Use item () to traverse a dictionary in Python

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.