Iterating Dictionaries with 'for' Loops
Dictionaries are crucial data structures in Python, and iterating over their elements is common. One way to iterate over a dictionary is using 'for' loops. But how does Python determine what to read from the dictionary?
Consider the code snippet:
d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(key, 'corresponds to', d[key])
This code prints key-value pairs from the dictionary. But how does Python know to iterate over the keys only?
The variable name key is arbitrary. It's not a special keyword that restricts iteration to keys. Python iterates over the keys because the 'for' loop is applied directly to the dictionary object d. Dictionaries are iterable collections, and when iterated over, they return their keys as the iteration variable.
However, to iterate over both keys and values simultaneously, use the following:
For Python 3.x:
for key, value in d.items():
For Python 2.x:
for key, value in d.iteritems():
This provides more flexibility in accessing both dictionary components.
The above is the detailed content of How Does Python Iterate Through Dictionaries Using 'for' Loops?. For more information, please follow other related articles on the PHP Chinese website!