Iterating over Dictionaries using 'for' Loops
Python provides a versatile mechanism to iterate over dictionaries using 'for' loops. This mechanism allows you to access either the keys or the key-value pairs of a dictionary.
By default, a 'for' loop that iterates over a dictionary yields the keys of the dictionary. This is because Python recognizes that the variable declared in the loop header (in this case, 'key') will serve as the key to access the corresponding values. Therefore, 'key' is not a special keyword, but simply a variable that holds the key for each iteration.
To iterate over both the keys and values of a dictionary, you need to explicitly specify the 'items()' method. In Python 3.x, the 'items()' method returns a view backed by the dictionary, which reflects any changes made to the dictionary after the 'items()' call. In Python 2.x, the 'items()' method returns a list of (key, value) pairs.
Here's a modified example:
d = {'x': 1, 'y': 2, 'z': 3} for key, value in d.items(): print(key, 'corresponds to', value)
This code will iterate over the keys and values of the dictionary, printing both the key and the corresponding value for each item. Note that 'key' and 'value' are simply variable names that can be changed to any valid Python identifier.
The above is the detailed content of How Can I Iterate Through Python Dictionaries Using For Loops?. For more information, please follow other related articles on the PHP Chinese website!