在本章中,你将学习能够将相关信息关联起来的Python字典,字典用于建模、储存信息。你将学到:
(1)定义与储存:如何定义字典,以及如何使用存储在字典中的信息;
(2)访问与修改:如何访问和修改字典中的元素,以及如何遍历字典中的所有信息;
(3)遍历:如何遍历字典中所有的键-值对、所有的键和所有的值;
(4)嵌套:如何在列表中嵌套字典、在字典中嵌套列表以及在字典中嵌套字典。
字典是一系列键-值对。字典用放在花括号{}中的一系列键—值对表示。键和值之间用冒号分隔,而键—值对之间用逗号分隔。在字典中,你想存储多少个键—值对都可以。
game={'object':'feifei','points':5}
new_points=game['points']
print(f'You get {new_points} points.')
字典是一种动态结构,可随时在其中添加键—值对。要添加键—值对,可依次指定字典名、用方括号括起的键和相关联的值。
创建空字典-添加值-修改值
game={'object':'feifei','character':'男孩'}
print(f"feifei is a {game['character']}.")
game['character']='女孩'
print(f"feifei is a {game['character']}.")
feifei={'x_position':0,'y_position':10,'speed':'medium'}
print(f"original x_position{feifei['x_position']}.")
if feifei['speed']=='medium':
x_increment=2
elif feifei['speed']=='slow':
x_increment=1
else:
x_increment=3
feifei['x_position']=feifei['x_position']+x_increment
print(feifei['x_position'])
Del [‘’]
favorite_food={
'feifei': 'shit',
'gdr': 'feifei',
'ashley':'chips'
}
print(f"feifei's favorite_food is: {favorite_food['feifei']}")
1.
feifei={'first_name':'Haifei','last_name':'Wang','gender':'effeminate'}
print(f'{feifei['first_name']},{feifei['last_name']},{feifei['gender']}')
2.
feifei={'hpz':1,'ashley':2,'feifei':3,'doudou':4,'lb':5}
print(f"hpz's favorite number is {feifei['hpz']}")
print(f"ashley's favorite number is {feifei['ashley']}")
print(f"feifei's favorite number is {feifei['feifei']}")
print(f"doudou's favorite number is {feifei['doudou']}")
print(f"lb's favorite number is {feifei['lb']}")
简化:
feifei={'hpz':1,'ashley':2,'feifei':3,'doudou':4,'lb':5}
for people,number in feifei.items():
print(f"{people.title()}'s favorite number is {number}")
3.
feifei={
'for':'循环',
'if':'条件',
'len':'确认列表长度',
'range':'创建数值列表'}
print(f" for:{feifei['for']} \n if:{feifei['if']} \n len:{feifei['len']} \n range:{feifei['range']} \n")
for k,v in user_0. Items () 循环
feifei={
'for':'循环',
'if':'条件',
'len':'确认列表长度',
'range':'创建数值列表'}
for key, definition in feifei.items():
print(f'The key word: {key}')
print(f'The answer is {definition} ')
注意,即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。
(1)遍历
feifei={'hpz':7,'ashley':2,'feifei':3,'doudou':4,'lb':5}
for people in feifei.keys():#提取feifei中的所有键,并储蓄到people中。
print(people.title())
Hpz
Ashley
Feifei
Doudou
Lb
feifei={'hpz':7,'ashley':2,'feifei':3,'doudou':4,'lb':5}
friends=['ashley','feifei']
for people in feifei.keys():#提取feifei中的所有键,并储蓄到people中。
print(people.title())
if people in friends:
print(f'Hi,{people},I know your favorite number is {feifei[people]}.')#记得给值索引。
(2)检查是不是在字典里
feifei={'hpz':7,'ashley':2,'feifei':3,'doudou':4,'lb':5}
if 'tony' not in feifei.keys():
print(f"Please tell me your favorite number.")
feifei={'hpz':7,'ashley':2,'feifei':3,'doudou':4,'lb':5}
for name in sorted(feifei.keys()):
print(f"{name},thank you for taking the polls.")
别忘了加s
feifei={'hpz':7,'ashley':2,'feifei':3,'doudou':4,'lb':5}
print('The following numbers are as mentioned:')
for numbers in feifei.values():
print(numbers)
如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的。
feifei={'hpz':7,'ashley':7,'feifei':3,'doudou':4,'lb':5}
print('The following numbers are as mentioned:')
for numbers in set(feifei.values()):
print(numbers)
6-5 河流:创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是'nile':'egypt'。
·使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
变量+对应:索引[变量]
rivers={'Yangtze River':'China','nile':'egypt','Amazon':'Brazil'}
for river in rivers:
print(f'The {river} runs through {rivers[river]}.')#对应:索引
·使用循环将该字典中每条河流的名字都打印出来。
rivers={'Yangtze River':'China','nile':'egypt','Amazon':'Brazil'}
for river in rivers.keys():#复数
print(river)
·使用循环将该字典包含的每个国家的名字都打印出来。
rivers={'Yangtze River':'China','nile':'egypt','Amazon':'Brazil'}
for nation in rivers.values():#复数
print(nation.title())
创造外星人
aliens=[]
for alien_number in range(30):#循环重复30次
new_alien={'color':'green','point':'5','speed':'slow'}
aliens.append(new_alien)
#显示前五个外星人
for alien in aliens[:5]:
print(alien)
print(f'The total number of aliens:{len(aliens)}')
这些外星人都具有相同的特征,但在Python看来,每个外星人都是独立的,这让我们能够独立地修改每个外星人。
修改值(if先判断,然后改)
aliens=[]
for alien_number in range(30):#循环重复30次
new_alien={'color':'green','point':'5','speed':'slow'}
aliens.append(new_alien)
#显示前五个外星人
for alien in aliens[:3]:
if alien['color']=='green':
alien['point']=10
alien['speed']='fast'
for alien in aliens[:5]:
print(alien)
print(f'The total number of aliens:{len(aliens)}')
随机赋值明显更有趣! random.choice(colors)
import random
aliens = []
colors = ['green', 'yellow', 'red']
for alien_number in range(30):
new_alien = {
'color': random.choice(colors),
'point': 5,
'speed': 'slow'
}
aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[:5]:
print(alien)
print(f'The total number of aliens:{len(aliens)}')
name={'people':'feifei',
'character':['insidious','huge','smart']}
print(f"{name['people']} is:")
for character in name['character']:
print(character)
1.好友信息
报错:
unhashable type: 'dict'
(unhashable=m utable)
dictionaries are mutable (can be changed), which makes them unhashable. In Python, keys of a dictionary must be hashable, and since dictionaries are mutable, they are not hashable.
feifei={}
yinyin={}
tony={}
people_all={
'feifei': {'gender':'effeminate','character':'smart','age':22},#记得添加''(字符串),不加就是变量,就是unhashable。
'yinyin': {'gender':'woman','character':'smart & beautiful','age':21},
'tony': {'gender':'man','character':'hardworking','age':21}
}
for people,details in people_all.items():
print(f"people:{people},details{details}")
2. 宠物信息
cats={}
dogs={}
fish={}
people_all={
'cats': {'category':'hello Kitty','owner':'feifei'},
'dogs': {'category':'哈巴狗','owner':'ashley'},
'fish': {'category':'三文鱼','owner':'tony'}
}
for category in people_all.keys():
print(f"category: {category}")
3. 人名+地方
favorite_places={
'hym':['英语课','家里','薅羊毛的饭店'],#列表后的comma不要忘记。
'hpz':['青岛','南通','长沙'],
'ttgg':['London','Tokyo','Rome']
}
for person, places in favorite_places.items():
print(f"{person}'s favorite places are:{','.join(places)}.")
hym's favorite places are:英语课,家里,薅羊毛的饭店.
hpz's favorite places are:青岛,南通,长沙.
ttgg's favorite places are:London,Tokyo,Rome.
4.
6-11 城市:创建一个名为cities的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country、population和fact等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'Beijing': {
'country': 'China',
'population': 21542000
},
'Tokyo': {
'country': 'Japan',
'population': 13960000
},
'New York': {
'country': 'United States',
'population': 8419600
}
}
for city, info in cities.items():
print(f"\nCity: {city}")
print(f"Country: {info['country']}")#表示索引
print(f"Population: {info['population']}")#表示索引