A simple way python loops through dictionary elements _python

Source: Internet
Author: User

A simple for statement loops through all the keys of the dictionary, just as it does with sequences:

In [1]: D = {' X ': 1, ' Y ': 2, ' Z ': 3} in

[2]: for key in D:
  ...:   print key, ' corresponds to ', D[key]
  ...: 
Y corresponds to 2
x corresponds to 1
z corresponds to 3

Before python2.2, you can only use the dictionary methods such as Beys to get the keys (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 the key-value pair as a tuple, and one of the benefits of the For loop is that the sequence can be used in loops:

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

Note: The Order of 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 uncertain. If the order is important, you can save the key values in a separate list, such as sorting before iterating.

This Python loop to iterate through the dictionary elements of the simple method is to share all the content of the small, hope to give you a reference, but also hope that we support the cloud habitat community.

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.