python中字典数据的嵌套:在字典中存储字典

还是套娃结构,字典中有字典,子子孙孙无穷匮,还是用逐层抽丝剥茧大法一点一点渗透进去,可以参考以下习题理解:
题目:创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含 country 、 population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
源代码解答:

cities = {
	"shanghai":{"area":"southeast China","population":2400,"fact":"SH is the modu city of China"},
	"beijing":{"area":"north China","population":3200,"fact":"BJ is the capital city of China"},
	"shenzhen":{"country":"south China","population":2200,"fact":"SZ is the near Hong Kong"}
}

for city in cities:
	print("the infomation of the city " + city.title() + " is as belows:")
	for k,v in cities[city].items():
		print(k+":"+str(v))
	print("***********************")

运行结果如下:

the infomation of the city Shanghai is as belows:
area:southeast China
population:2400
fact:SH is the modu city of China
***********************
the infomation of the city Beijing is as belows:
area:north China
population:3200
fact:BJ is the capital city of China
***********************
the infomation of the city Shenzhen is as belows:
country:south China
population:2200
fact:SZ is the near Hong Kong
***********************
[Finished in 0.6s]

你可能感兴趣的:(python基础数据类型)