目录
6.1 简单字典
>>> alien_0={'color':'green','points':5}
>>> print(alien_0['color'])
green
>>> print(alien_0['points'])
5
6.2 字典使用
字典是一系列键-值对,每个键都与一个值相关联。可用键访问与之关联的值。
字典放在花括号中的一系列键-值对表示。 键和值之间用冒号分隔,而键—值对之间用逗号分隔。
1.访问
2.添加
字典是动态结构,可添加键-值对
>>> alien_0
{'color': 'green', 'points': 5}
>>> alien_0['x']=0
>>> alien_0['y']=25
>>> alien_0
{'color': 'green', 'points': 5, 'x': 0, 'y': 25}
键-值对的排练顺序与添加顺序不一定相同
3.创建空字典
>>> alien_0={}
>>> alien_0['color']='green'
>>> alien_0['points']=5
>>> alien_0
{'color': 'green', 'points': 5}
4.修改字典值
>>> alien_0['points']=10
>>> alien_0
{'color': 'green', 'points': 10}
5.删除键-值对
可使用del删除键-值对,需指定字典名及其键
>>> alien_0
{'color': 'green', 'points': 10}
>>> del alien_0['color']
>>> alien_0
{'points': 10}
6.由类似对象组成的字典
>>> favorite_languages={
... 'jen':'python',
... 'sarah':'c',
... 'edward':'c++',
... 'phil':'python',
... }
>>> favorite_languages
{'jen': 'python', 'sarah': 'c', 'edward': 'c++', 'phil': 'python'}
>>> print(favorite_languages['edward'])
c++
6.3 遍历字典
1.遍历键-值对
若要访问字典中所有信息,使用for循环遍历字典
>>> user={'name':'efermi','first':'enrico','last':'fermi'}
>>> for key,value in user.items():
... print(key)
... print(value)
...
name
efermi
first
enrico
last
fermi
需声明两个用于存储的变量。 items() 函数以列表返回可遍历的(键, 值) 元组数组。
2.遍历键
>>> favorite_languages={'jen':'python','sarah':'c','edward':'rudy','phil':'c++'}
>>> for name in favorite_languages.keys():
... print(name)
...
jen
sarah
edward
phil
>>> if 'curry' not in favorite_languages.keys():
... print("查无此人")
...
查无此人
遍历字典时,默认遍历所有键。
keys():返回键值
3.按顺序遍历键
字典获取时,顺序不可预测,可使用sorted()获得按特定顺序排列的键
>>> for name in sorted(favorite_languages.keys()):
... print(name)
...
edward
jen
phil
sarah
sorted()将对字典内键按字母顺序排列
4.遍历字典中的值
values()可以返回列表中的值
>>> favorite_languages={'jen':'python','sarah':'c','edward':'rudy','phil':'c++'}
>>> for language in favorite_languages.values():
... print(language)
...
python
c
rudy
c++
若字典值中含重复项,可使用集合set
>>> favorite_languages={'jen':'python','sarah':'c','edward':'rudy','phil':'c'}
>>> for language in set(favorite_languages.values()):
... print(language)
...
c
rudy
python
6.4嵌套
将列表存储在字典或将字典存储在列表内,称为嵌套
1.字典列表
>>> alien_0={'color':'green','points':5}
>>> alien_1={'color':'red','points':10}
>>> alien_2={'color':'black','points':15}
>>> aliens=[alien_0,alien_1,alien_2]
>>> aliens
[{'color': 'green', 'points': 5}, {'color': 'red', 'points': 10}, {'color': 'black', 'points': 15}]
2.字典中存储列表
>>> pizza={
... 'crust':'thick',
... 'toppings':['mushrooms','extra cheese'],
... }
>>> pizza
{'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese']}
>>> for topping in pizza['toppings']:
... print('\t'+topping)
...
mushrooms
extra cheese
3.在字典中存储字典
>>> users={
... 'ayton':{'first':'albert','last':'ainstein','location':'princeton'},
... 'paul':{'first':'marie','last':'curie','location':'paris'},
... }
>>> for username,user_info in users.items():
... print(username)
... location=user_info['location']
... print(location)
...
ayton
princeton
paul
paris
作业
1.使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中的每项信息都打印出来。
>>> info={'first':'stephen','last':'curry','age':'33','location':'golden state'}
>>> print(info)
{'first': 'stephen', 'last': 'curry', 'age': '33', 'location': 'golden state'}
>>> print(info['first'])
stephen
>>> print(info['last'])
curry
>>> print(info['location'])
golden state
>>> print(info['age'])
33
2.使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。
>>> favorite_numbers={'cuury':'30','jordon':'23','james':'23','kobe':'24','johnson':'13'}
>>> favorite_numbers
{'cuury': '30', 'jordon': '23', 'james': '23', 'kobe': '24', 'johnson': '13'}
3.创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是'nile': 'egypt' 使用循环为每条河流打印一条消息,如“The Nileruns throughEgypt.”。使用循环将该字典中每条河流的名字都打印出来。使用循环将该字典包含的每个国家的名字都打印出来
>>> country_river={'The Yellow river':'china','nile':'egypt','the gangers':'indian'}
>>> for key,value in country_river.items():
... print(key+' runs through '+value)
...
The Yellow river runs through china
nile runs through egypt
the gangers runs through indian
#打印河流
>>> for river in country_river.keys():
... print(river)
...
The Yellow river
nile
the gangers
#打印国家
>>> for country in country_river.values():
... print(country)
...
china
egypt
indian
4.在6.3.1节编写的程序favorite_languages.py中执行以下操作。创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查
#源代码
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())
#改进代码
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'}
friends=['jen','edward','kun','ford']
for name in friends:
if name in favorite_languages.keys():
print(name+' thank you')
else:
print(name+' welcome to our survey')
5想出你在前面学过的5个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符(\n )插入一个空行,然后在下一行以缩进的方式打印词汇的含义。
j_words={'pr1nt':"1",'ture':'2','false':'3','1nput':'4','0utput':'5'}
for word,mean in j_words.items():
print(word+': '+mean+'\n')
>>> info_0={'first': 'stephen', 'last': 'curry', 'age': '33', 'location': 'golden state'}
>>> info_1={'first': 'michelle', 'last': 'jordan', 'age': '45', 'location': 'chicago'}
>>> info_2={'first': 'lebron', 'last': 'james', 'age': '36', 'location': 'los angeles'}
>>> people=[info_0,info_1,info_2]
>>> people
[{'first': 'stephen', 'last': 'curry', 'age': '33', 'location': 'golden state'}, {'first': 'michelle', 'last': 'jordan', 'age': '45', 'location': 'chicago'}, {'first': 'lebron', 'last': 'james', 'age': '36', 'location': 'los angeles'}]
>>> for info in people:
... print(info)
...
{'first': 'stephen', 'last': 'curry', 'age': '33', 'location': 'golden state'}
{'first': 'michelle', 'last': 'jordan', 'age': '45', 'location': 'chicago'}
{'first': 'lebron', 'last': 'james', 'age': '36', 'location': 'los angeles'}
7.创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
答:略
8.创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places={'curry':['golden state','beijing','shanghai'],
'james':['los angeles','miami','cleveland'],'paul':['new orleans','phoenix','houston']}
for name,places in favorite_places.items():
print(name+'like:')
for place in places:
print(place)
print('\n')
currylike:
golden state
beijing
shanghai
jameslike:
los angeles
miami
cleveland
paullike:
new orleans
phoenix
houston
9.修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来。
favorite_numbers={'cuury':['30','31','32'],'jordon':['34','23'],'james':['6','23'],'kobe':['8','24'],'johnson':'13'}
for name,numbers in favorite_numbers.items():
print(name+' like number:')
for number in numbers:
print(number)
cuury like number:
30
31
32
jordon like number:
34
23
james like number:
6
23
kobe like number:
8
24
johnson like number:
1
3
10.创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities={
'beijing':{
'country':'china',
'people':'20 million',
'fact':'the capital'},
'oaklan':{
'country':'U.S.A',
'people':'400000',
'fact':'warrior'},
'shanghai':{
'country':'china',
'people':'24 million',
'fact':'wealth'}
}
for name,info in cities.items():
print(name.title())
for key,value in info.items():
print(key+': '+value)
print('\n')
Beijing
country: china
people: 20 million
fact: the capital
Oaklan
country: U.S.A
people: 400000
fact: warrior
Shanghai
country: china
people: 24 million
fact: wealth