Python字典键值遍历的一个问题

Yu_jose 2018-01-20 01:08:58
river = {
'nile' : 'egypt',
'yangtze' : 'china',
'YellowRiver' : 'china'
}
for country in river.values():
print(country.title())
for name in river.keys():
print(name.title())
for river,country in river.items():
print(end='The {} run through '.format(river))
print(country )


如上代码是可以正常运行的,但只要把最后一个for循环提前放到前两个for循环前面就会有异常,这是为什么??
比如说,作如下改动

river = {
'nile' : 'egypt',
'yangtze' : 'china',
'YellowRiver' : 'china'
}
for country in river.values():
print(country.title())
for river, country in river.items():
print(end='The {} run through '.format(river))
print(country)
for name in river.keys():
print(name.title())



运行结果是:
...全文
347 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Yu_jose 2018-01-20
  • 打赏
  • 举报
回复
引用 1 楼 oyljerry 的回复:
你遍历的名字也是river,影响原来字典了,改名一下 for river_name, country in river.items():
for循环里面那个river和country不是可以随便命名的吗? 怎么影响到原来的字典的?
oyljerry 2018-01-20
  • 打赏
  • 举报
回复
你遍历的名字也是river,影响原来字典了,改名一下 for river_name, country in river.items():

37,718

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧