6-2 喜欢的数字:
favorite_number = {
'alex' : 29,
'leo' : 23,
'mike' : 45,
'John' : 100,
'Phil' : 34,
}
输出:
Alex's favorite number is 29.
Leo's favorite number is 23.
Mike's favorite number is 45.
John's favorite number is 100.
Phil's favorite number is 34.
6-5 河流
rivers = {
'China': 'Changjiang',
'egypt': 'nile',
'brazil' : 'amazon'
}
print("Messages:")
for river in rivers:
print("The " + river.title() + " runs through " + rivers[river].title() + '.')
print("\nThe following rivers have been mentioned:")
for river in rivers.keys():
print(river.title())
print("\nThe following countries have been mentioned: ")
for country in rivers.values():
print(country.title())
输出:
Messages:
The China runs through Changjiang.
The Egypt runs through Nile.
The Brazil runs through Amazon.
The following rivers have been mentioned:
China
Egypt
Brazil
The following countries have been mentioned:
Changjiang
Nile
Amazon
6-6 调查
favorite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
visited_friends = ['jen', 'sarah']
for name in favorite_language.keys():
if name in visited_friends:
print(name.title() + ",you participated in the survey,thank you!")
else:
print(name.title() + ",would you like to join us?")
输出:
Jen,you participated in the survey,thank you!
Sarah,you participated in the survey,thank you!
Edward,would you like to join us?
Phil,would you like to join us?
6-8 宠物:
pets = {
'lili':{
'type' : 'cat',
'people' : 'alex',
},
'jordon':{
'type': 'dog',
'people': 'mike',
},
'jucy':{
'type': 'bird',
'people': 'leo',
}
}
for name, infos in pets.items():
print("\nName: " + name.title())
print("\tType: " + infos['type'].title())
print("\tHost: " + infos['people'].title())
输出:
Name: Lili
Type: Cat
Host: Alex
Name: Jordon
Type: Dog
Host: Mike
Name: Jucy
Type: Bird
Host: Leo
6-10 喜欢的数字:
favorite_number = {
'jen': [23,45,34],
'sarah': [45,78],
'phil':[35,100,556,789],
}
for name, numbers in favorite_number.items():
print("\n" + name.title() + "'s favorite numbers are: ")
for number in numbers:
print("\t" + str(number))
输出:
Jen's favorite numbers are:
23
45
34
Sarah's favorite numbers are:
45
78
Phil's favorite numbers are:
35
100
556
789
6-12 扩展
删去键和值:
favorite_number = {
'jen': [23,45,34],
'sarah': [45,78],
'phil':[35,100,556,789],
}
del favorite_number['jen']
for name, numbers in favorite_number.items():
print("\n" + name.title() + "'s favorite numbers are: ")
for number in numbers:
print("\t" + str(number))
输出:
Sarah's favorite numbers are:
45
78
Phil's favorite numbers are:
35
100
556
789