Home >Backend Development >Python Tutorial >Introduction to two ways of looping through dictionaries in python
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.
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
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!