6-1 人:使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。
该字典应包含键 first_name、 last_name、 age 和 city。将存储在该字典中的每项信息都打印出来。
person = {
'first_name': 'Iverson',
'last_name': 'Allen',
'age': 32,
'city': 'NYC',
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
运行结果:
Iverson
Allen
32
NYC
6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。请想出 5 个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
favorite_numbers = {
'xiaoming': 21,
'xiaohong': 1,
'xiaofang': 6,
'xianoli': 18,
'xiaowang': 3,
}
num = favorite_numbers['xiaoming']
print("xiaoming's favorite number is " + str(num) + ".")
num = favorite_numbers['xiaohong']
print("xiaohong's favorite number is " + str(num) + ".")
num = favorite_numbers['xiaofang']
print("xiaofang's favorite number is " + str(num) + ".")
num = favorite_numbers['xianoli']
print("xianoli's favorite number is " + str(num) + ".")
num = favorite_numbers['xiaowang']
print("xiaowang's favorite number is " + str(num) + ".")
运行结果:
xiaoming's favorite number is 21.
xiaohong's favorite number is 1.
xiaofang's favorite number is 6.
xianoli's favorite number is 18.
xiaowang's favorite number is 3.
6-3 词汇表: Python 字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
#想出你在前面学过的 5 个编程词汇,将它们用作词汇表中的键,
#并将它们的含义作为值存储在词汇表中。
glossary = {
'string': 'A series of characters.',
'comment': 'A note in a program that the Python interpreter ignores.',
'list': 'A collection of items in a particular order.',
'loop': 'Work through a collection of items, one at a time.',
'dictionary': "A collection of key-value pairs.",
}
#以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加
#上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符(\n)
#插入一个空行,然后在下一行以缩进的方式打印词汇的含义
word = 'string'
print("\n" + word.title() + ": " + glossary[word])
word = 'comment'
print("\n" + word.title() + ": " + glossary[word])
word = 'list'
print("\n" + word.title() + ": " + glossary[word])
word = 'loop'
print("\n" + word.title() + ": " + glossary[word])
word = 'dictionary'
print("\n" + word.title() + ": " + glossary[word])
运行结果:
String: A series of characters.
Comment: A note in a program that the Python interpreter ignores.
List: A collection of items in a particular order.
Loop: Work through a collection of items, one at a time.
Dictionary: A collection of key-value pairs.
6-4 词汇表 2:既然你知道了如何遍历字典,现在请整理你为完成练习 6-3 而编写的代码,将其中的一系列 print 语句替换为一个遍历字典中的键和值的循环。确定该循环正确无误后,再在词汇表中添加 5 个 Python 术语。当你再次运行这个程时,这些新术语及其含义将自动包含在输出中。
glossary = {
'string': 'A series of characters.',
'comment': 'A note in a program that the Python interpreter ignores.',
'list': 'A collection of items in a particular order.',
'loop': 'Work through a collection of items, one at a time.',
'dictionary': "A collection of key-value pairs.",
'key': 'The first item in a key-value pair in a dictionary.',
'value': 'An item associated with a key in a dictionary.',
'conditional test': 'A comparison between two values.',
'float': 'A numerical value with a decimal component.',
'boolean expression': 'An expression that evaluates to True or False.',
}
for word, definition in glossary.items():
print("\n" + word.title() + ": " + definition)
运行结果:
String: A series of characters.
Comment: A note in a program that the Python interpreter ignores.
List: A collection of items in a particular order.
Loop: Work through a collection of items, one at a time.
Dictionary: A collection of key-value pairs.
Key: The first item in a key-value pair in a dictionary.
Value: An item associated with a key in a dictionary.
Conditional Test: A comparison between two values.
Float: A numerical value with a decimal component.
Boolean Expression: An expression that evaluates to True or False.
6-5 河流:创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—
值对可能是’nile’: ‘egypt’。
#使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
rivers = {
'nile' : 'egypt',
'yangtze' : 'china',
'amazon' : 'brazil',
}
for river, country in rivers.items():
print('The ' + river.title() +' runs through '
+ country.title() + '.')
#使用循环将该字典中每条河流的名字都打印出来。
print("\nThe following rivers are included in this data set:")
for river in rivers.keys():
print(river.title())
#使用循环将该字典包含的每个国家的名字都打印出来。
print("\nThe following countries are included in this data set:")
for country in rivers.values():
print(country.title())
运行结果:
The Nile runs through Egypt.
The Yangtze runs through China.
The Amazon runs through Brazil.
The following rivers are included in this data set:
Nile
Yangtze
Amazon
The following countries are included in this data set:
Egypt
China
Brazil
6-6 调查:在 6.3.1 节编写的程序 favorite_languages.py 中执行以下操作。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
#创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
#遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,
#打印一条消息邀请他参与调查。
coders = ['phil', 'josh', 'david', 'becca', 'sarah', 'matt', 'danielle']
for coder in coders:
if coder in favorite_languages.keys():
print("Thank you for taking the poll, " + coder.title() + "!")
else:
print(coder.title() + ", what's your favorite programming language?")
运行结果:
Thank you for taking the poll, Phil!
Josh, what's your favorite programming language?
David, what's your favorite programming language?
Becca, what's your favorite programming language?
Thank you for taking the poll, Sarah!
Matt, what's your favorite programming language?
Danielle, what's your favorite programming language?
6-7 人:在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,然后将这
三个字典都存储在一个名为 people 的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。
person_0 = {
'first_name':'Iveron',
'last_name':'Allen',
'age':23,
'city':'NYC'
}
person_1 = {
'first_name':'Jordan',
'last_name':'Michael',
'age':30,
'city':'Chicago'
}
person_2 = {
'first_name':'Jianlian',
'last_name':'Yi',
'age':28,
'city':'Guangdong'
}
people = [person_0,person_1,person_2]
for person in people:
name = person['first_name'].title() + " " + person['last_name'].title()
age = str(person['age'])
city = person['city'].title()
print(name + ", of " + city + ", is " + age + " years old.")
运行结果:
Iveron Allen, of Nyc, is 23 years old.
Jordan Michael, of Chicago, is 30 years old.
Jianlian Yi, of Guangdong, is 28 years old.
6-8 宠物:创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为 pets 的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
cloris = {
'type' : 'dog',
'host' : 'john'
}
brinkley = {
'type' : 'cat',
'host' : 'lucy',
}
pets = [cloris,brinkley]
for pet in pets:
for key, value in pet.items():
print(key + ": " + str(value))
运行结果:
type: dog
host: john
type: cat
host: lucy
6-9 喜欢的地方:创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的 1~3 个地方。为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_place = {
'jen' : ['Beijing','Shanghai'],
'sarah' : ['Dalian'],
'edward' : ['Chengdu','Beijing','Nanjing'],
}
for name, citys in favorite_place.items():
print('\n' + 'name:' + name)
for city in citys:
print('\t' + 'city: '+ city)
运行结果:
name:jen
city: Beijing
city: Shanghai
name:sarah
city: Dalian
name:edward
city: Chengdu
city: Beijing
city: Nanjing
6-10 喜欢的数字:修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字以及喜欢的数字打印出来。
favorite_num = {
'jen' : [2,5],
'sarah' : [8],
'edward' : [1,3,5],
}
for name, nums in favorite_num.items():
print('\n' + 'name:' + name)
for num in nums:
print('\t' + 'num: '+ str(num))
运行结果:
name:jen
num: 2
num: 5
name:sarah
num: 8
name:edward
num: 1
num: 3
num: 5
6-11 城市:创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城
市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含 country、 population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'Beijing' : {
'country' : 'China',
'population' : 22000000,
'fact' : 'aaaaa',
},
'Shanghai' : {
'country' : 'China',
'population' : 25000000,
'fact' : 'bbbbbb',
},
'NewYork' : {
'country' : 'America',
'population' : 8500000,
'fact' : 'cccccc',
},
}
for city, city_infos in cities.items():
print('\n' + 'city: ' + city)
print('\t' + 'country: ' + city_infos['country'])
print('\t' + 'population: '+ str(city_infos['population']))
print('\t' + 'fact: '+ city_infos['fact'])
运行结果:
city: Beijing
country: China
population: 22000000
fact: aaaaa
city: Shanghai
country: China
population: 25000000
fact: bbbbbb
city: NewYork
country: America
population: 8500000
fact: cccccc