Dictionariception
还记得列表吗?列表可以包含任何东西,甚至是其他列表。实际上,字典也一样。字典的值也可以是字典,即由键值对组成。
例如,请查看脚本中另一版的 europe(您一直在使用的字典)。键仍然是国家名称,但值是包含比首都更多信息的字典。
您可以串联方括号来选择元素。例如,从 europe 中获取西班牙的人口,您需要:
europe['spain']['population']
本练习是课程的一部分
Python 中级
练习说明
- 使用串联的方括号选择并打印法国的首都。
- 创建一个名为
data的字典,包含键'capital'和'population'。分别将它们设为'rome'和59.83。 - 向
europe添加一个新的键值对;键为'italy',值为您刚构建的字典data。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Dictionary of dictionaries
europe = { 'spain': { 'capital':'madrid', 'population':46.77 },
'france': { 'capital':'paris', 'population':66.03 },
'germany': { 'capital':'berlin', 'population':80.62 },
'norway': { 'capital':'oslo', 'population':5.084 } }
# Print out the capital of France
# Create sub-dictionary data
# Add data to europe under key 'italy'
# Print europe