Explain the two ways of looping through a dictionary in python

  • 2020-05-26 09:22:41
  • OfStack

Looping through dictionaries, lists and other data is often used in development. However, the looping through dictionaries in python is very unfamiliar to many beginners. Today, I will introduce two ways of looping through dictionaries in python.

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

1. Only traverse the keys

A simple for statement loops through all the keys of the dictionary, just like processing sequence 1:


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

You can use d.values if you only need values, or d.keys if you want to get all the keys.

The d.items method returns the key-value pair as a tuple if you want to retrieve the key and value. The first great benefit 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 undefined. In other words, when iterating, the keys and values in the dictionary are guaranteed to be processed, but in an uncertain order. If order is important, you can save the keys in a separate list, such as sorting before iteration.


Related articles: