#6.4.1 字典列表
#有时候,需要将一系列字典存储在列表中,后将列表值存储在字典中,这称为嵌套。你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典嵌套字典。正如下面的示例
#将演示的,嵌套是一项强大的功能。
#===============================
#创建一个用于存储外星人的列表。
aliens = []
#创建30个绿色的外星人。
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
#对字典进行修改。
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = '10'
# for alien in aliens[:3]:
if alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = '15'
#显示前5个外星人。
for aline in aliens[:5]:
print(aline)
print("...")
#显示创建了多少个外星人。
print(f"Total number of aliens:{len(aliens)}")
#========================================================
#6.4.2 在字典中存储列表
#有时候,需要将列表存储在字典中,而不是将字典存储在列表中。
#存储所点披萨的信息。
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
#概述所点披萨。
print(f"You ordered a {pizza['crust']}-crust pizza"'\t'
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
#=================================================
#在字典中存储字典。
#可在字典中嵌套字典,但这样做时,代码可能很快复杂起来。例如,如果有多个网站用户,每个都有独特的用户名,可将字典中每个用户名作为键,然后将每位用户的信
#息存储在一个字典中,并将该字典作为与用户相关联的值。
#==================================================
users = {
'fangqi':{
'first':'fang',
'last':'qi',
'location':'jiangxi',
},
'mengyu':{
'first':'meng',
'last':'yu',
'location':'jiangxi',
},
}
for username,user_info in users.items():
print(f"\nUsername:{username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name:{full_name.title()}\n\tLocation:{location.title()}")
#要注意的是,表示每位用户的字典都具有相同的结构。虽然Python没有这样的要求,但这可以使嵌套的字典处理起来的更容易。
#练习
#=============================
# 创建三个表示人的字典,然后将三个字典存储在一个名为people的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。
people = []
user_0 = {
'first':'fang',
'last':'qi',
}
user_1 = {
'first':'ma',
'last':'qi',
}
user_2 = {
'first':'meng',
'last':'yu',
}
people = [user_0,user_2,user_1]
for username in people:
print(username)
#=========================
#在字典中,将三个人的名字作为键,并存储每个喜欢的1~3个地方。遍历这个字典,并将每个人的名字和其喜欢的地方打印出来。
favorite_places = {
'fangqi':['xizang','suhzou'],
'mengyu':['sanya'],
'mayongqi':['taizhou'],
}
for name,places in favorite_places.items():
if len(places) >1:
print(f"{name} like to place are :")
else:
print(f"{name} like go to place is :")
for place in places:
print(f'\t{place.title()}'
)
#=========================================
#创建一个字典,将三个城市名作为键。对于每座城市,都创建一个字典,并包含该城市所属的国家、人口、以及有关这个城市的事实。
cities = {
'jiangxi': {
'country':'China',
'population':'452 million',
'fact':'Examination and teaching resources',
},
'Tokyo':{
'country':'Japan',
'population':'13 million 500 thousand',
'fact':'Toilet water has been used as drinking water for nearly 30 years',
},
'New York':{
'country':'USA',
'population':'8.62 million people',
'fact':'NYPD nabs man accused of punching 11-year-old girl in Manhattan park',
},
}
for city_name,city_info in cities.items():
print(f"Cityname:{city_name.title()}")
country = city_info['country']
population = city_info['population']
fact = city_info['fact']
print(f"\tCountry:{country}\n\tPupolation:{population.title()}\n\tFact:{fact.title()}")