d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
Python如何识别它只需要从字典中读取key
? key
是一个特殊的关键字,还是只是一个变量?
最佳答案
key
只是一个变量名。
for key in d:
将简单地遍历字典中的键,而不是键和值。要遍历键和值,您可以使用以下内容:
对于 Python 3.x:
for key, value in d.items():
对于 Python 2.x:
for key, value in d.iteritems():
要自己测试,请将单词 key
更改为 poop
。
在 Python 3.x 中,iteritems()
被简单地替换为 items()
,它返回由 dict 支持的类似集合的 View ,如 iteritems()
但更好。
这在 2.7 中也可以作为 viewitems()
使用。
items()
操作适用于 2 和 3,但在 2 中它将返回字典的 (key, value)
对的列表,这将不反射(reflect)在 items()
调用之后发生的对 dict 的更改。如果你想要 3.x 中的 2.x 行为,你可以调用 list(d.items())
。
关于python - 使用 'for' 循环遍历字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3294889/