1.一个简单的字典
alien_o={'color':'green','point':5}
print(alien_o['color'])
print(alien_o['point'])
字典aline_0存储外星人的颜色和点数。
结果:
green
5
2.使用字典
在python中,字典是一系列键-值对。每个键都与一个值相关联,可以使用键来访问与之相关联的键。与键相关联的值可以是数字、字符串、列表、乃至字典。事实上,任何python对象都可以作为字典中的值。
字典用放在花括号{}中的一系列键-值对表示,键-值对之间用逗号分隔。
2.1访问字典中的值
alien_o={'color':'green','point':5}
new_points=alien_o['point']
print("You just earned "+str(new_points)+" point!")
结果:
You just earned 5 point!
2.2添加键-值对
字典是一种动态结构,可随时在其中添加键-值对。要添加键-值对,可依次指定字典名、用方括号括起的键和相关联的值。如在字典alien_0中添加外星人的坐标。
alien_o={'color':'green','point':5}
print(alien_o)
alien_o['x_position']=0
alien_o['y_position']=25
print(alien_o)
结果:
{'color': 'green', 'point': 5}
{'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}
2.3先创建一个空字典
有时候,在空字典中添加键-值对是为了方便,而有时必须这样做。
alien_o={}
alien_o['color']='green'
alien_o['point']=5
print(alien_o)
结果:
{'color': 'green', 'point': 5}
2.4修改字典中的值
alien_o={'color':'green'}
print("The alien is " + alien_o['color'] + ".")
alien_o['color']='yellow'
print("The alien is now " + alien_o['color'] + ".")
结果:
The alien is green.
The alien is now yellow.
2.5删除键-值对
对于字典中不再需要的信息,可使用del语句将相适应的键-值对彻底删除。使用del语句时,必须指定字典名和需要删除的键。
alien_o={'color':'green','point':5}
print(alien_o)
del alien_o['point']
print(alien_o)
结果:
{'color': 'green', 'point': 5}
{'color': 'green'}
2.6由类似对象组成的字典
前面的示例,字典存储的是一个对象的多种信息,也可以用字典来存储众多对象的同一种信息。
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
print("Sarah's favourite language is "
+ favourite_languages['sarah'].title() +
".")
结果:
Sarah's favourite language is C.
3.遍历字典
3.1遍历所有的键-值对
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
for name,language in favourite_languages.items():
print(name.title() + "'s favourite language is " + language.title() +".")
结果:
Jen's favourite language is Python.
Sarah's favourite language is C.
Edward's favourite language is Ruby.
Phil's favourite language is Python.
3.2遍历字典中的所有键
在不需要使用字典中的值时,可以使用方法keys()
如下,吧所有调查者的名字打印出来:
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
for name in favourite_languages.keys():
print(name.title())
结果:
Jen
Sarah
Edward
Phil
又例如:
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
friends = ['phil','sarah']
for name in favourite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() +
", I see your favourite language is " +
favourite_languages[name].title() + "!")
结果:
Jen
Sarah
Hi Sarah, I see your favourite language is C!
Edward
Phil
Hi Phil, I see your favourite language is Python!
3.3按顺序遍历字典中的所有键
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
friends = ['phil','sarah']
for name in sorted(favourite_languages.keys()):
print(name.title() + ",thank you for taking the poll.")
结果:
Edward,thank you for taking the poll.
Jen,thank you for taking the poll.
Phil,thank you for taking the poll.
Sarah,thank you for taking the poll.
3.4遍历字典中的所有值
如果你感兴趣的主要是字典包含的值,可以使用values(),它返回一个值列表,而不包含任何键。
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
print("The following language have been mentioned:")
for language in favourite_languages.values():
print(language.title())
结果:
The following language have been mentioned:
Python
C
Ruby
Python
这种做法提取字典中的所有值,不考虑是否重复。如果涉及的值过多,会包含大量重复项。为剔除重复项,可以使用集合(set),集合类似于列表,每个元素都是独一无二的。
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
print("The following language have been mentioned:")
for language in set(favourite_languages.values()):
print(language.title())
结果:
The following language have been mentioned:
C
Python
Ruby
4.嵌套
有时候需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。
4.1字典列表
先创建三个字典,每个字典代表一个外星人。将字典都放在列表中,遍历列表。
alien_o = {'color':'green','points':5}
alien_1 = {'color':'yellow',"points":10}
alien_2 = {'color':'red','points':15}
aliens=[alien_o,alien_1,alien_2]
for alien in aliens:
print(alien)
结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
4.2在字典中存储列表
favourite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell']
}
for name,languages in favourite_languages.items():
print("\n" + name.title() + "'s favourite languages are:")
for language in languages:
print("\t" + language.title())
#languages 存储字典中的值,这些值都是列表,language存储列表中的值
结果:
Jen's favourite languages are:
Python
Ruby
Sarah's favourite languages are:
C
Edward's favourite languages are:
Ruby
Go
Phil's favourite languages are:
Python
Haskell
注意:列表和字典的嵌套层级不应太多。
4.3在字典中存储字典
可以在字典中嵌套字典,但是可能会让代码复杂。
users = {
'aesinstein':{
'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())
结果:
Username: aesinstein
Full name: Albert·Einstein
Location: Princeton
Username: mcurie
Full name: Marie·Curie
Location: Paris
注意:表示每位用户的字典结构相同,虽然python没有这样要求,但是,这样处理起来更容易。否则,for循环内部的语句会非常复杂。