字典和循环
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典和循环相关的知识,希望对你有一定的参考价值。
创建一个名为城市的字典 在你的字典中使用三个城市的名称作为键 创建一个关于每个城市的信息字典,并包括该城市所在的国家、其大约的人口和关于该城市的一个事实 每个城市的字典的键应该是类似于国家、人口和事实的东西 打印每个城市的名称和你所存储的关于它的所有信息。
我的代码。
cities=
"Egy":
"name":"egypt",
"capital":"cairo",
"population": "100,000",
"fact":"civilization"
,
"leb":
"name":"lebanon",
"capital":"beiruit",
"population": "10,000",
"fact":"beautiful"
,
"moroc" :
"name":"morocco",
"capital":"rabat",
"population": "1000,000",
"fact":"food"
for city, city_info in cities.items():
print ("I love "+ city+ " and here's what I know about it: ")
for info in city_info:
print("the full name of the country is " + city_info["name"] + " its capital is " + city_info["capital"]+
" the number of population is "+ city_info["population"] + " the most famous fact about it is " + city_info["fact"])
我想把这两个循环一起打印出来 这样每个国家就会变成一句话(我还没学过函数)
答案
没有必要进行第二个循环,你可以简单地这样做。
for city, city_info in cities.items():
print ("I love "+ city+ " and here's what I know about it: the full name of the country is " + city_info["name"] + " its capital is " + city_info["capital"]+
" the number of population is "+ city_info["population"] + " the most famous fact about it is " + city_info["fact"])
这将产生以下输出:
I love Egy and here's what I know about it: the full name of the country is egypt its capital is cairo the number of population is 100,000 the most famous fact about it is civilization
I love leb and here's what I know about it: the full name of the country is lebanon its capital is beiruit the number of population is 10,000 the most famous fact about it is beautiful
I love moroc and here's what I know about it: the full name of the country is morocco its capital is rabat the number of population is 1000,000 the most famous fact about it is food
以上是关于字典和循环的主要内容,如果未能解决你的问题,请参考以下文章