6-7 人:在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为 people 的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。
6-8 宠物:创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为 pets 的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
6-9 喜欢的地方:创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的 1~3 个地方。为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
6-10 喜欢的数字:修改为完成练习 6-2 而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来。
6-11 城市:创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含 country、population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
6-12 扩展:本章的示例足够复杂,可以以很多方式进行扩展了。请对本章的一个示例进行扩展:添加键和值、调整程序要解决的问题或改进输出的格式。
#6-7
people={
'name1':{
'first_name':'wang',
'last_name':'kai',
'age':27,
'city':'hangzhou'
},
'name2':{
'first_name':'qiu',
'last_name':'liyuan',
'age':24,
'city':'xian'
},
'name3':{
'first_name':'guo',
'last_name':'yuanyuan',
'age':24,
'city':'shandong'
}
}
for name,messages in people.items():
print('\nUsername:'+name)
full_name=messages['first_name']+' '+messages['last_name']
age=str(messages['age'])
city=messages['city']
print('\tFull name:'+full_name.title())
print('\tAge:'+age)
print('\tCity:'+city.title())
#6-8宠物
ketty={'dog':'wangkai'}
mily={'cat':'qiuliyuan'}
cang={'mouse':'guoyuanyuan'}
pets=[ketty,mily,cang]
for pet in pets:
print(pet)
#喜欢的地方
favorite_places={
'qiuliyuan':['zhucheng','xinjiang','xizang'],
'wangkai':['hangzhou','shanghai','beijing'],
'guoyuanyuan':['qingdao','chengdu']
}
for name,cities in favorite_places.items():
print('\nName:'+name.title()+"'s favorite city are:")
for city in cities:
print('\t'+city)
#6-10喜欢的数字
favorite_numbers={
'dog':[1,2,3,5],
'kat':[3,5,6],
'monkey':[7,8],
'john':[7,8,9],
'mary':[66,77,88],
}
for name,nums in favorite_numbers.items():
print('\n'+name.title()+' like:')
num=str(nums)
print('\t'+num)
#6-11
cities={
'taiwan':{
'country':'china',
'population':'general',
'fact':'zhongguod'
},
'jiujinshan':{
'country':'us',
'population':'most',
'fact':'rich'
}
}
for city,messages2 in cities.items():
print('\nName:'+name.title())
country=messages2['country']
population=messages2['population']
fact=messages2['fact']
print('\tCountry:'+country.title())
print('\tPopulation:'+population)
print('\tFact:'+fact)