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.