Python3 学习笔记(五)字典
参考书籍《Python编程:从入门到实践》【美】Eric Matthes
使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中的每项信息都打印出来。
friend = {
'first_name': 'Cannon',
'last_name': 'Fly',
'age': 25,
'city': 'Chendu'
}
print(friend['first_name'])
print(friend['last_name'])
print(friend['age'])
print(friend['city'])
创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是’nile’: ‘egypt’ 。使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
rivers = {
'nile': 'egypt',
'amazon': 'brasil',
'changjiang': 'china',
}
for river, country in rivers.items():
print('The ' + river.title() + ' runs through ' + country.title())
创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
persons = ['jen', 'god', 'edward']
for name, language in favorite_languages.items():
if name in persons:
print(name.title() + ', thanks for your participation')
else:
print(name.title() + ', invite you to participate a research')
将三个字典都存储在一个名为people 的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。
person_1 = {
'name': 'cannon',
'age': 25
}
person_2 = {
'name': 'god',
'age': 24
}
person_3 = {
'name': 'leg',
'age': 27
}
people = [ person_1, person_2, person_3 ]
for person in people:
print(person['name'].title() + ' is ' + str(person['age']) + ' years old')
创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places = {
'cannon': ['Paris', 'Lodon', 'Tokyo'],
'god': ['Lodon', 'New York'],
'leg': ['Shanghai']
}
for name, places in favorite_places.items():
print(name.title() + ' loves:')
for place in places:
print(place)
创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'Paris': {
'country': 'France',
'population': 11000000,
'fact': 'romantic'
},
'Berlin': {
'country': 'Germany',
'population': 3500000,
'fact': 'beer'
},
'New York': {
'country': 'American',
'population': 8510000,
'fact': 'rich'
},
}
for city, desc in cities.items():
print(city + "'s information:")
for key, value in desc.items():
print(key + ': ' + str(value))