key
is just a variable name.
(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: (要遍历键和值,可以使用以下命令:)
For Python 2.x:
(对于Python 2.x:)
for key, value in d.iteritems():
For Python 3.x:
(对于Python 3.x:)
for key, value in d.items():
To test for yourself, change the word key
to poop
.
(要进行自我测试,请将单词key
更改为poop
。)
For Python 3.x, iteritems()
has been replaced with simply items()
, which returns a set-like view backed by the dict, like iteritems()
but even better.
(对于Python 3.x, iteritems()
已替换为简单的items()
,它返回了由dict支持的类似set的视图,就像iteritems()
但效果更好。)
This is also available in 2.7 as viewitems()
. (在2.7中也可以通过viewitems()
。)
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.
(操作items()
将同时适用于2和3,但是在2中它将返回字典的(key, value)
对的列表,该列表将不反映对items()
调用后字典的更改。)
If you want the 2.x behavior in 3.x, you can call list(d.items())
. (如果要在3.x中使用2.x行为,可以调用list(d.items())
。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…