2 回答
TA贡献1799条经验 获得超8个赞
顺便说一句,你已经嵌套了dicts。你没有任何sets。
您的意思是这样吗:
for name,value in country.items():
print(f'capital city of {name} is {value["capital"]}')
输出:
capital city of spain is madrid
capital city of france is paris
capital city of germany is berlin
capital city of norway is oslo
capital city of peru is lima
更新:我在语句中使用了 an f-stringin print(),这有时是一种更简单的格式化字符串的方法。
TA贡献1886条经验 获得超2个赞
迭代字典country并使用值打印适当的大写字母key:
country = {
'spain': { 'capital':'madrid', 'population':46.77 },
'france': { 'capital':'paris', 'population':66.03 },
'germany': { 'capital':'berlin', 'population':80.62 },
'norway': { 'capital':'oslo', 'population':5.084 },
'peru' : {'capital':'lima', 'population':250}
}
for country, capitals in country.items():
print("Country: {0}, Capital: {1}".format(country, capitals['capital']))
输出:
Country: peru, Capital: lima
Country: germany, Capital: berlin
Country: spain, Capital: madrid
Country: france, Capital: paris
Country: norway, Capital: oslo
编辑:
单行:
print([{"Country: {0}, Capital: {1}".format(cn, cp['capital'])} for cn, cp in country.items()])
输出:
[{'Country: spain, Capital: madrid'}, {'Country: germany, Capital: berlin'}, {'Country: norway, Capital: oslo'}, {'Country: france, Capital: paris'}, {'Country: peru, Capita
l: lima'}]
添加回答
举报