A simple way for Python to iterate through a dictionary element

Source: Internet
Author: User
Here is an easy way for you to iterate through the dictionary elements in a python loop. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

A simple for statement can loop all the keys of a dictionary, just as you would with a sequence:


In [1]: D = {' X ': 1, ' Y ': 2, ' z ': 3}in [2]:-Key in D:  ...:   print key, ' corresponds to ', D[key]  ...: y Corresp Onds to 2x corresponds to 1z corresponds to 3


Before python2.2, you can only use the dictionary method such as Beys to get the key (because the dictionary is not allowed to iterate directly). If you only need values, you can use d.values instead of D.keys. The D.items method returns a key-value pair as a tuple, and one of the great benefits of a For loop is that the sequence can be used to unpack in a loop:


In [4]: for key, value in D.items ():  ...:   print key, ' corresponds to ', Value  ...: y corresponds to 2x correspo NDS to 1z corresponds to 3


Note: The order of the dictionary elements is usually undefined. In other words, when iterating, the keys and values in the dictionary are guaranteed to be processed, but the processing order is indeterminate. If the order is important, you can save the key values in a separate list, such as before the iteration.

Above this Python loop to iterate through the dictionary elements of the simple method is the small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support a lot of topic.alibabacloud.com.

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.