The following editor will bring you a simple method of looping through dictionary elements in python. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.
A simple for statement can loop through all the keys of the dictionary, just like processing sequences:
In [1]: d = {'x':1, 'y':2, 'z':3} In [2]: for key in d: ...: print key, 'corresponds to', d[key] ...: y corresponds to 2 x corresponds to 1 z corresponds to 3
Before python2.2, you could only use dictionary methods such as beys to obtain keys (because direct iteration of the dictionary was not allowed). If you only need values, you can use d.values instead of d.keys. The d.items method will return key-value pairs as tuples. One of the great benefits of the for loop is that you can use sequence unpacking in the loop:
In [4]: for key, value in d.items(): ...: print key, 'corresponds to', value ...: y corresponds to 2 x corresponds to 1 z corresponds to 3
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 simple method of python looping through dictionary elements is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.
For more related articles on the simple method of python looping through dictionary elements, please pay attention to the PHP Chinese website!