小能豆

Iterating over dictionaries using 'for' loops

py

d = {'x': 1, 'y': 2, 'z': 3}

for key in d:
    print(key, 'corresponds to', d[key])

How does Python recognize that it needs only to read the key from the dictionary? Is key a special keyword, or is it simply a variable?


阅读 63

收藏
2023-12-16

共1个答案

小能豆

In Python, the for key in d construct is used to iterate over the keys of a dictionary (d in your example). The variable key is not a special keyword; it’s just a variable name that you can choose. In each iteration, key takes on the value of one of the keys in the dictionary.

When you iterate over a dictionary using for key in d, Python iterates over the keys of the dictionary by default. The loop variable (key in this case) is assigned each key in turn, and you can use it to access the corresponding values in the dictionary.

Here’s how the loop works:

  1. In the first iteration, key is assigned the value of the first key in the dictionary ('x' in your example).
  2. In the second iteration, key is assigned the value of the second key ('y').
  3. In the third iteration, key is assigned the value of the third key ('z').

The loop continues until all keys have been processed.

You can also iterate over values, key-value pairs, or items by using the values(), items(), or iter() methods. For example:

# Iterating over values
for value in d.values():
    print('Value:', value)

# Iterating over key-value pairs
for key, value in d.items():
    print('Key:', key, 'Value:', value)

In summary, key is just a variable, and the for key in d syntax is a convenient way to iterate over the keys of a dictionary.

2023-12-16