Python's versatility extends to its ability to iterate over dictionaries using 'for' loops. Consider the following code:
d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(key, 'corresponds to', d[key])
This code prints the keys and corresponding values from the dictionary. But how does Python know to read only the keys?
The Nature of 'key'
Contrary to misconception, 'key' is not a reserved keyword in Python. It is simply a variable name used in the 'for' loop. Python doesn't have special syntax to access dictionary keys.
Looping Over Keys Only
When iterating over a dictionary using a 'for' loop, Python 默认 iterates over the keys in the dictionary. This is because dictionaries are implemented as hash tables, where each key is associated with a unique value. By iterating over the keys, Python can access the corresponding values through the dictionary square brackets notation (d[key]).
Looping Over Keys and Values
If both keys and values are needed in the loop, the following syntax is used:
For Python 3.x:
for key, value in d.items():
For Python 2.x:
for key, value in d.iteritems():
However, in Python 3.x, the iteritems() method was replaced with items() which provides a better, set-like view backed by the dictionary.
Testing the Variable Name
To confirm that 'key' is a regular variable, one can change it to any other name, for example 'poop':
for poop in d: print(poop, 'corresponds to', d[poop])
This code will produce the same output, demonstrating that 'key' is not a reserved term.
The above is the detailed content of How Does Python Iterate Over Dictionary Keys Using a 'for' Loop?. For more information, please follow other related articles on the PHP Chinese website!