Here is an easy way for you to iterate through the dictionary elements in a python loop. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
A simple for statement can loop all the keys of a dictionary, just as you would with a sequence:
In [1]: D = {' X ': 1, ' Y ': 2, ' z ': 3}in [2]:-Key in D: ...: print key, ' corresponds to ', D[key] ...: y Corresp Onds to 2x corresponds to 1z corresponds to 3
Before python2.2, you can only use the dictionary method such as Beys to get the key (because the dictionary is not allowed to iterate directly). If you only need values, you can use d.values instead of D.keys. The D.items method returns a key-value pair as a tuple, and one of the great benefits of a For loop is that the sequence can be used to unpack in a loop:
In [4]: for key, value in D.items (): ...: print key, ' corresponds to ', Value ...: y corresponds to 2x correspo NDS to 1z corresponds to 3
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.
Above this Python loop to iterate through the dictionary elements of the simple method is the small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support a lot of topic.alibabacloud.com.