Introduction to the two methods of dictionary looping in python

Source: Internet
Author: User
It is often used in development to traverse the dictionary, list, and other data cyclically. However, in python, dictionary traversal is very unfamiliar to many beginners, today, we will talk about the circular traversal of dictionary and list data in python, but the dictionary traversal in python is very unfamiliar to many beginners, today, let's talk about the two methods of looping dictionary in python.

Note: in python2 and python3, the following two methods are common.

1. only key traversal

A simple for statement can loop all the keys of the dictionary, just like the processing 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 keys and values

If you only need a value, you can use d. values. if you want to obtain all the keys, you can use d. keys.

If you want to obtain the key and value d. items method, the key-value pair will be returned as a tuple. a major benefit of the for loop is that sequential unpacking can be used 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 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 above is a detailed description of the two methods of circular traversal of the dictionary in python. For more information, see other related articles in the first PHP community!

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.