例题6-5
描述:创建字典,存储三条大河流及其流经国家。
打印指定消息,分别打印全部河流和国家。
代码:
river_country = {
'yellow river': 'china',
'nile': 'egypt',
'amazon river': 'brazil',
}
for river,country in river_country.items():
print('The ' + river.title() +
' runs through ' +
country.title() +
'.')
print('Rivers:')
for river in river_country.keys():
print(river.title())
print('\nCountries:')
for country in river_country.values():
print(country.title())
结果:
例题6-9 喜欢的地方
描述:创建favorite_places字典,将三个人的名字用作键;
对于其中的每个人,都存储他喜欢的1~3个地方。
把名字和地方打印。
扩展:创建后在字典中添加一个人,打印字典和长度,再删除,重复。
代码:
favorite_places = {
'Eric': ['Japan', 'Africa', 'China'],
'Ponyo': ['Australia', 'Finland', 'Japan'],
'Reading': ['Singapore', 'Japan', 'China'],
}
favorite_places['Mary'] = ['England', 'America', 'Korea']
for people in favorite_places.keys():
print('\nName: ' + people)
print('Places: ')
for place in favorite_places[people]:
print(place)
print(len(favorite_places))
del favorite_places['Mary']
print(len(favorite_places))
for people in favorite_places.keys():
print('\nName: ' + people)
print('Places: ')
for place in favorite_places[people]:
print(place)
结果:
例题6-11
描述:创建cities字典,三个城市名用作键;对于每座城市,
都创建一个字典,并在其中包含该城市所属的国家、
人口约数以及一个有关该城市的事实。
在表示每座城市的字典中,应包含country 、
population 和fact 等键。
将每座城市的名字以及有关它们的信息都打印出来。
代码:
cities = {
'Guangzhou': {
'Country': 'China',
'Population': '14.4984million',
'Fact': 'Many delicious foods here.',
},
'Seoul': {
'Country': 'Korea',
'Population': '10.14 million',
'Fact': 'Cosmetics shopping paradise.',
},
'Brisbane': {
'Country': 'Australia',
'Population': '2.27million',
'Fact': 'Fantastic weather.',
},
}
for city in cities.keys():
print('\n' + city + ':')
for key,value in cities[city].items():
print(key + ': ', end='')
print(value)
结果:
发现的问题:
- 对于key,value不要忘记items keys values
- 字典的值为字典时要注意,创建时不要忘记逗号(在一项结束后)。
- python一行的字数有限制 要注意换行和缩进的规范(字典,print),不要忘记逗号(最好在字典的最后一项也加上逗号)。