Two ways to iterate through a dictionary in Python

Source: Internet
Author: User
It is often used in development to iterate through the data such as dictionaries , lists, and so on, but the traversal of a dictionary in Python is unfamiliar to many beginners, and today it is two ways to iterate through a dictionary in Python.

Note: The following two methods are common in Python2 and Python3.

1. Traversal of keys only

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

D = {' name1 ': ' Pythontab ', ' name2 ': '. ', ' name3 ': ' com '}for key in D:    print (Key, ' Value: ', D[key]) name1 value: Pythontabname2 value:. Name3 value:com


2. Traverse both the key and the value

If you only need a value, you can use D.values and you can use D.keys if you want to get all the keys.

If you want to get the keys and values the D.items method returns a key-value pair as a tuple, one of the great benefits of a For loop is that you can use the sequence unpacking in a loop.

code example:

For key, value in D.items ():    print (Key, ' Value: ', value) name1 value:pythontabname2 value:. Name3 value:com


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.

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.