Python: A simple method to traverse dictionary elements cyclically.

Source: Internet
Author: User

Python: A simple method to traverse dictionary elements cyclically.

A simple for statement can loop all the keys of the dictionary, just like the processing sequence:

In [1]: d = {'X': 1, 'y': 2, 'z': 3} In [2]: for key in d :...: print key, 'corresponds to ', d [key]...: y corresponds to 2x corresponds to 1z corresponds to 3

Before python2.2, keys can only be obtained using dictionary methods such as beys (because direct dictionary iteration is not allowed ). If you only need a value, you can use d. values instead of d. keys. D. The items method returns key-value pairs as tuples. A major benefit of the for Loop is that sequential unpacking can be used in a loop:

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

Note:The order of dictionary elements is usually not defined. In other words, keys and values in the dictionary can be processed during iteration, but the processing sequence is uncertain. If the order is important, you can save the key values in a separate list, such as sorting before iteration.

The Simple Method for Traversing dictionary elements in the above python loop is to share all the content with you. I hope to give you a reference and support for the help house.

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.