遍历字典
在 Python 3 中,您需要使用 items() 方法来遍历字典:
world = { "afghanistan":30.55,
"albania":2.77,
"algeria":39.21 }
for key, value in world.items() :
print(key + " -- " + str(value))
还记得 europe 字典吗?它以一些欧洲国家名为键,以其首都为对应的值。请编写一个循环来遍历它吧!
本练习是课程的一部分
Python 中级
练习说明
编写一个 for 循环,遍历 europe 的每个 key:value 对。在每次迭代中,打印 "the capital of x is y",其中 x 是键,y 是对应的值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
# Iterate over europe