5174
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()替换为
simple items(),它返回由dict支持的类似set的视图,
iteritems()但效果更好。在2.7中也可用
viewitems()。
该操作
items()将对2和3都适用,但是在2中,它将返回字典
(key, value)对的列表,该列表将不反映
items()调用之后对dict所做的更改。如果要在3.x中使用2.x行为,可以调用
list(d.items())。



