Home  >  Article  >  Backend Development  >  Introduction to two ways of looping through dictionaries in python

Introduction to two ways of looping through dictionaries in python

高洛峰
高洛峰Original
2017-03-16 16:09:321634browse

Looptraversal of dictionaries, lists and other data are often used in development, but the traversal of dictionaries in python is difficult for many beginners Very unfamiliar, today I will talk about two ways of looping through dictionaries in python.

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

1. Traversing only keys

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

d = {'name1' : 'pythontab', 'name2' : '.', 'name3' : 'com'}
for key in d:
    print (key, ' value : ', d[key])
name1 value : pythontab
name2 value : .
name3 value : com


2. Traverse both keys and values

If you only need the values, you can use d.values. If you want to get all the keys, you can use d. keys.

If you want to get the key and value, the d.items method will return the key-value pair as a tuple. One of the benefits of the for loop is that you can use sequence unpacking in the loop.

Code example:

for key, value in d.items():
    print (key, ' value : ', value)
name1 value : pythontab
name2 value : .
name3 value : com


Note: The order of dictionary elements is usually not defined. In other words, when iterating, the keys and values ​​in the dictionary are guaranteed to be processed, but the processing order is uncertain. If order is important, you can save the key values ​​in a separate list, for example to sort before iterating.


The above is the detailed content of Introduction to two ways of looping through dictionaries in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn