第 6 章 字典
6.1 一个简单的字典
automatic_rifle = {'M4A1':'5.56','AK47':'7.62'}
print(automatic_rifle['M4A1'])
print(automatic_rifle['AK47'])
5.56
7.62
6.2.1 访问字典中的值
zd ={'lx':'5.56','sl':'30'}
hdzd = zd['sl']
print("你刚获得了"+str(hdzd) +"发5.56子弹")
你刚获得了30发5.56子弹
6.2.2 添加键 — 值对
zd ={'lx':'5.56','sl':'30'}
zd['rifle1'] ='SCAR'
zd['rifle2'] ='M4A1'
print(zd)
{'rifle2': 'M4A1', 'lx': '5.56', 'sl': '30', 'rifle1': 'SCAR'}
6.2.4 修改字典中的值
zd ={'lx':'5.56','sl':'30'}
zd['lx'] ='7.62'
print(zd)
{'sl': '30', 'lx': '7.62'}
6.2.5 删除键 — 值对
zd ={'lx':'5.56','sl':'30'}
delzd['sl']
print(zd)
{'lx': '5.56'}
注意 删除的键 — 值对永远消失了。
6.2.6 由类似对象组成的字典
aotomatic_rlfle = {
'5.56':'M4A1',
'7.62':'Groza',
'9mm':'UMP',
'0.56mm':'Vecot'
}
print(aotomatic_rlfle['5.56'].lower())
m4a1
6.3.1 遍历所有的键 — 值对
words = {'individual':'个人的','constant':'恒定的','chaper':'章节',
'division':'除法','misunderstanding':'误会','unwavering':'坚定不移的'}
forkey,valueinwords.items():
print('\n'+ key +"\n"+ value)
chaper
章节
misunderstanding
误会
unwavering
坚定不移的
constant
恒定的
division
除法
individual
个人的
'M4A1''SCAR':'5.56',
'AK47':'7.62'
}
fork,vinautomatic_rifle.items():
print(k +"use bullet about "+ v +".")
M4A1SCARuse bullet about 5.56.
AK47use bullet about 7.62.
要编写用于遍历字典的 for 循环,可声明两个变量,用于存储键 — 值对中的键和值。对于这两个变量,可使用任何名称。
6.3.2 遍历字典中的所有键
players = {
'chenyi':'caiji',
'songyuqing':'caiji',
'xiaomeng':'niubi'
}
forninplayers.keys():
print(n)
chenyi
songyuqing
xiaomeng
players = {
'chenyi':'caiji',
'songyuqing':'caiji',
'm1':'niubi'
}
lihai = ['m1']
forninplayers:
ifninlihai:
print(n +"你特么真厉害")
m1你特么真厉害
你还可以使用 keys() 确定元素是否在字典里。
players = {
'chenyi':'caiji',
'songyuqing':'caiji',
'm1':'niubi'
}
if'zhucong'not inplayers.keys():
print('zhucong小菜鸡')
zhucong小菜鸡
6.3.3 按顺序遍历字典中的所有键
players = {
'chenyi':'caiji',
'songyuqing':'caiji',
'm1':'niubi'
}
forninsorted(players.keys()):
print(n)
chenyi
m1
songyuqing
以首字母先后排序
6.3.4 遍历字典中的所有值
players = {
'chenyi':'caiji',
'songyuqing':'caiji',
'm1':'niubi'
}
forninplayers.values():
print(n)
caiji
caiji
niubi
这种做法提取字典中所有的值,而没有考虑是否重复。涉及的值很少时,这也许不是问,但如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合( set )。 集合 类似于列表,但每个元素都必须是独一无二的:
players = {
'chenyi':'caiji',
'songyuqing':'caiji',
'm1':'niubi'
}
forninset(players.values()):
print(n)
caiji
niubi
automatic_rifles = []
forautomatic_rifle_numbersinrange(30):
new_gun = {'ammo':'5.56','ammo2':'7.62','ammo3':'9mm'}
automatic_rifles.append(new_gun)
forautomatic_rifleinautomatic_rifles[:5]:
print(automatic_rifle)
print("...")
print(str(len(automatic_rifles)))
{'ammo': '5.56', 'ammo3': '9mm', 'ammo2': '7.62'}
{'ammo': '5.56', 'ammo3': '9mm', 'ammo2': '7.62'}
{'ammo': '5.56', 'ammo3': '9mm', 'ammo2': '7.62'}
{'ammo': '5.56', 'ammo3': '9mm', 'ammo2': '7.62'}
{'ammo': '5.56', 'ammo3': '9mm', 'ammo2': '7.62'}
...
30
automatic_rifles = []
forautomatic_rifle_numbersinrange(30):
new_gun = {'ammo':'5.56','ammo2':'7.62','ammo3':'9mm'}
automatic_rifles.append(new_gun)
forautomatic_rifleinautomatic_rifles[:3]:
ifautomatic_rifle['ammo'] =='5.56':
automatic_rifle['ammo'] ='12'
automatic_rifle['ammo2'] ='0.45mm'
forautomatic_rifleinautomatic_rifles[:5]:
print(automatic_rifle)
print("...")
print(str(len(automatic_rifles)))
{'ammo2': '0.45mm', 'ammo3': '9mm', 'ammo': '12'}
{'ammo2': '0.45mm', 'ammo3': '9mm', 'ammo': '12'}
{'ammo2': '0.45mm', 'ammo3': '9mm', 'ammo': '12'}
{'ammo2': '7.62', 'ammo3': '9mm', 'ammo': '5.56'}
{'ammo2': '7.62', 'ammo3': '9mm', 'ammo': '5.56'}
...
30
6.4.2 在字典中存储列表
adpet_languages = {
'kevin': ['python','c'],
'thomas': ['c++'],
'bradley': ['ruby','go']
}
forkey,valueinadpet_languages.items():
print(key.title() +"'s adpet languages are")
fora_linvalue:
print(a_l.title())
Bradley's adpet languages are
Ruby
Go
Thomas's adpet languages are
C++
Kevin's adpet languages are
Python
C
6.4.3 在字典中存储字典
Celtics_players = {
'KI':{
'f_n':'kyrie',
'l_n':'irving',
'wz':'pg',
},
'GH':{
'f_n':'gordon',
'l_n':'harward',
'wz':'sf',
},
'AF': {
'f_n':'al',
'l_n':'horford',
'wz':'pf'
}
}
forplayer,infoinCeltics_players.items():
print("Let's welcome "+ player +"!")
full = info['f_n'] +" "+ info['l_n']
wz = info['wz']
print("His full name is "+ full)
print("He play in "+ wz +"\n")
Let's welcome KI!
His full name is kyrie irving
He play in pg
Let's welcome AF!
His full name is al horford
He play in pf
Let's welcome GH!
His full name is gordon harward
He play in sf
6-8 宠物 :创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为 pets的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
pets = {
'pug': {
'name':'mib',
'hosts': ['ma','mb'],
'hobbys': ['eat','drink']
},
'huskie': {
'name':'2b',
'hosts':['mc'],
'hobbys': ['distory']
},
'bulldog': {
'name':'cute',
'hosts': ['md','me','mf'],
'hobbys': ['sleep','eat']
},
}
fordog,infoinpets.items():
print("It is a pet ----"+ dog +"!")
name = info['name']
hosts = info['hosts']
hobbys = info['hobbys']
print("Its name is "+ name +".")
forhostinhosts:
print(host +" is it master!")
forhobbyinhobbys:
print("It always like "+ hobby)
It is a pet ----pug!
Its name is mib.
ma is it master!
mb is it master!
It always like eat
It always like drink
It is a pet ----huskie!
Its name is 2b.
mc is it master!
It always like distory
It is a pet ----bulldog!
Its name is cute.
md is it master!
me is it master!
mf is it master!
It always like sleep
It always like eat
6-9喜欢的地方 :创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的 1~3 个地方。为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places = {
'kevin': ['shanghai','nanjing'],
'brooks': ['beijing','guangzhou'],
'davis': ['xizang','neimenggu']
}
forname,placesinfavorite_places.items():
print(name.title() +" like those places:")
forplaceinplaces:
print(place.title())
Kevin like those places:
Shanghai
Nanjing
Brooks like those places:
Beijing
Guangzhou
Davis like those places:
Xizang
Neimenggu
6-10 喜欢的数字 :修改为完成练习 6-2 而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来。
lucky_numbers = {
'a':['1','4','5'],
'b':['2','6','7'],
'c':['3','8','9']
}
forname,lnsinlucky_numbers.items():
print(name +"'s lucky numbers is:")
forlninlns:
print(ln)
a's lucky numbers is:
1
4
5
b's lucky numbers is:
2
6
7
c's lucky numbers is:
3
8
9
6-11 城市 :创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含 country 、 population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'shanghai': {
'country':'china',
'population':'24.15million',
'fact':'apartments is too expensive to afford.'
},
'tokyo': {
'country':'japen',
'population':'13.50million',
'fact':'emmmmmmmmm,I will visit the city someday.maybe.'
},
'boston': {
'country':'america',
'population':'4.5million',
'fact':'Celtics!'
}
}
forcity,infoincities.items():
print(city +":")
country = info['country']
population = info['population']
fact = info['fact']
print(country +"\n"+population +"\n"+ fact +"\n")
shanghai:
china
24.15million
apartments is too expensive to afford.
tokyo:
japen
13.50million
emmmmmmmmm,I will visit the city someday.maybe.
boston:
america
4.5million
Celtics!
领取专属 10元无门槛券
私享最新 技术干货