使用“for"循环迭代字典 [英] Iterating over dictionaries using 'for' loops
问题描述
我对下面的代码有点困惑:
I am a bit puzzled by the following code:
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print (key, 'corresponds to', d[key])
我不明白的是 key
部分.Python如何识别它只需要从字典中读取键?key
在 Python 中是一个特殊的词吗?或者它只是一个变量?
What I don't understand is the key
portion. How does Python recognize that it needs only to read the key from the dictionary? Is key
a special word in Python? Or is it simply a variable?
推荐答案
key
只是一个变量名.
for key in d:
将简单地遍历字典中的键,而不是键和值.要遍历键和值,您可以使用以下内容:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
对于 Python 3.x:
For Python 3.x:
for key, value in d.items():
对于 Python 2.x:
For Python 2.x:
for key, value in d.iteritems():
要自己测试,请将单词 key
更改为 poop
.
To test for yourself, change the word key
to poop
.
在 Python 3.x 中,iteritems()
被简单地替换为 items()
,它返回一个由 dict 支持的类似集合的视图,如 iteritems()
但更好.这在 2.7 中也可以作为 viewitems()
使用.
In Python 3.x, iteritems()
was replaced with simply items()
, which returns a set-like view backed by the dict, like iteritems()
but even better.
This is also available in 2.7 as viewitems()
.
操作 items()
对 2 和 3 都有效,但在 2 中它将返回字典的 (key, value)
对的列表,这将不反映在 items()
调用之后发生的对 dict 的更改.如果你想要 3.x 中的 2.x 行为,你可以调用 list(d.items())
.
The operation items()
will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value)
pairs, which will not reflect changes to the dict that happen after the items()
call. If you want the 2.x behavior in 3.x, you can call list(d.items())
.
这篇关于使用“for"循环迭代字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!