Python第六章
# 6.1 一个简单的字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# 6.2 使用字典
# 6.2.1 访问字典中的值
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print("You just earned " + str(new_points) + "points!")
# 6.2.2 添加键——值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
# 外星人的x坐标和y坐标
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 6.2.3 先创建一个空字典
alien_0 = {}
print(alien_0)
# 分行添加各个键值对
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
# 6.2.4 修改字典中的值
alien_0 = {'color': 'green', 'points': 5}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
# 对一个能够以不同速度移动的外星人的位置进行跟踪
# 存储外星人的当前速度,并确定该外星人将向右移动多远
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_0['x_position']))
# 向右移动外星人
# 根据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3 # 这个外星人的速度一定很快
# 新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x_position: " + str(alien_0['x_position']))
# 6.2.5 删除键——值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
# 6.2.6 由类似对象组成的字典
# 调查4个人,询问他们最喜欢的编程语言是什么
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
".")
# 6-1 使用一个字典来存储一个熟人的信息
person = {
'first_name': 'eric',
'last_name': 'matthes',
'age': 66,
'city': 'sitka',
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
# 6-2 喜欢的数字
favorite_numbers = {
'mandy': 42,
'micah': 33,
'gus': 6,
'hank': 1000000,
'maggie': 0,
}
num = favorite_numbers['mandy']
print("Mandy's favorite number is " + str(num) + ".")
num = favorite_numbers['micah']
print("Micah's favorite number is " + str(num) + ".")
num = favorite_numbers['gus']
print("Gus's favorite number is " + str(num) + ".")
num = favorite_numbers['hank']
print("Hank's favorite number is " + str(num) + ".")
num = favorite_numbers['maggie']
print("Maggie's favorite number is " + str(num) + ".")
# 6-3 词汇表
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.',
}
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])
# 6.3 遍历字典
# 6.3.1 遍历所有的键——值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
# 6.3.2 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " + name.title() + ", I see you favorite language is " + favorite_languages[name].title() + "!")
# 使用keys() 确定某个人是否接受了调查
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
# 6.3.3 按顺序遍历字典中的所有键(字典总是明确地记录键和值之间的关联关系,但获取字典的元素时,获 取顺序是不可预测的。)
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
# 6.3.4 遍历字典中的所有值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()): # set()的作用是找出列表中独一无二的元素,并使用这些元素来创建一个集合(输出序列乱序)
print(language.title())
# 6-4 词汇表2
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) # 或者用下面的两句
# for name in glossary.keys():
# print("\n" + name.title() + ": " + glossary[name])
# 6-5 河流
rivers = {
'nile': 'egypt',
'mississippi': 'united states',
'fraser': 'canada',
'kuskokwim': 'alaska',
'yangtze': 'china',
}
for river, country in rivers.items():
print("The " + river.title() + " flows through " + country.title() + ".")
print("\nThe following rivers are included in this data set:")
for river in rivers.keys():
print("- " + river)
print("\nThe following countries are included in this data set:")
for country in rivers.values():
print("- " + country.title())
# 6-6 调查
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
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?")
# 6.4 嵌套
# 6.4.1 字典列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
# 创建一个用于存储外星人空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[:5]:
print(alien)
print("......")
# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
# 创建一个用于存储外星人空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:3]: # 把前三个中绿色外星人换成黄色外星人,黄色外星人换成红色外星人
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 10
alien['speed'] = 'medium'
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['points'] = 15
alien['speed'] = 'fast'
# 显示前五个外星人
for alien in aliens[:5]:
print(alien)
print("......")
# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
# 6.4.2 在字典中存储列表
# 存储所点披萨的信息
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
# 概述所点披萨
print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
if len(languages) == 1:
print("\n" + name.title() + "'s favorite language is:")
else:
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
# 6.4.3 在字典中存储字典
# 多个网站用户,每个用户都有自己独特的用户名,字典里用户名为键
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
# 6-7 按要求打印列表中的字典信息
people = []
person = {
'first_name': 'eric',
'last_name': 'matthes',
'age': 43,
'city': 'sitka',
}
people.append(person)
person = {
'first_name': 'ever',
'last_name': 'matthes',
'age': 5,
'city': 'sitka',
}
people.append(person)
person = {
'first_name': 'willie',
'last_name': 'matthes',
'age': 8,
'city': 'sitka',
}
people.append(person)
for person in people:
name = person['first_name'] + " " + person['last_name']
age = str(person['age'])
city = person['city']
print(name.title() + ", of " + city.title() + ", is " + age + " years old.")
# 6-8 宠物
pets = []
pet = {
'animal type': 'cat',
'name': 'john',
'owner': 'guido',
'weight': 43,
'eats': 'bugs',
}
pets.append(pet)
pet = {
'animal type': 'chicken',
'name': 'clarence',
'owner': 'tiffany',
'weight': 2,
'eats': 'seeds',
}
pets.append(pet)
pet = {
'animal type': 'dog',
'name': 'peso',
'owner': 'eric',
'weight': 36,
'eats': 'shoes',
}
pets.append(pet)
for pet in pets:
print("\nHere's what I know about " + pet['name'].title() + ":")
for key, value in pet.items():
print("\t" + key + ": " + str(value))
# 6-9 喜欢的地方
favorite_places = {
'eric': ['bear mountain', 'death valley', 'tierra del fuego'],
'erin': ['hawaii', 'iceland'],
'ever': ['mt. verstovia', 'the playground', 'south carolina'],
}
for name, places in favorite_places.items():
print("\n" + name.title() + "'s favorite places are:")
for place in places:
print("- " + place.title())
# 6-10 喜欢的数字
favorite_numbers = {
'mandy': [42, 17, 66],
'micah': [23, 33, 36],
'gus': [7, 6, 3],
'hank': [1000000, 999999, 666666,],
'maggie': [0, 3, 6],
}
for name, numbers in favorite_numbers.items():
print("\n" + name.title() + "'s favorite numbers are:")
for number in numbers:
print("- " + str(number))
# 6-11 城市
cities = {
'santiago': {
'country': 'chile',
'population': 6158080,
'nearby mountains': 'andes',
},
'talkeetna': {
'country': 'alaska',
'population': 876,
'nearby mountains': 'alaska range',
},
'kathmandu': {
'country': 'nepal',
'population': 1008600,
'nearby mountains': 'himilaya',
},
}
for city, city_info in cities.items():
country = city_info['country'].title()
population = city_info['population']
mountains = city_info['nearby mountains'].title()
print("\n" + city.title() + "is in " + country + ".")
print("\tIt has a population of about " + str(population) + ".")
print("\tThe " + mountains + " mountains are nearby.")

浙公网安备 33010602011771号