文章目录
1. 字典简介
- 字典是由一系列键值对组成,每个键都与一个值相关联,与键相关联的值可以是数字、字符串、列表、甚至是字典
- 字典名 = {键1:值1,键2:值2,依此类推}
- 最简单的字典只有一个键值对
alien_0 ={'color':'green'}
2. 字典使用
要获取与键相关联的值,可依次指定字典名、放在方括号内的键名
alien_0 ={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
green
5
2.1 访问字典中的值
>>> alien_0 ={'color':'green','points':5}
>>> new_points = alien_0['points']
>>> print("You just earned "+str(new_points)+" points!")
You just earned 5 points!
2.2 添加键—值对
- 字典是一种动态结构,可随时在其中添加键—值对
- 添加键值对,依次指定字典名、用方括号括起的键、相关联的值
- 注意:键—值对的排列顺序与添加顺序不同,Python不关心键—值对的添加顺序,只关心键—值对之间的关联关系**
>>> alien_0 ={'color':'green','points':5}
>>> print(alien_0)
{'color': 'green', 'points': 5}
>>> alien_0['x_position'] = 0
>>> alien_0['y_position'] = 25
>>> print(alien_0)
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
2.3 删除键—值对
- 使用del 语句将相应的键—值对彻底删除
- 使用del 语句,必须指定字典名、要删除的键
>>> alien_0 ={'color':'green','points':5}
>>> print(alien_0)
{'color': 'green', 'points': 5}
>>> del alien_0['points']
>>> print(alien_0)
{'color': 'green'}
2.4 先创建一个空字典
使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时,通常需要先定义一个空字典
>>> alien_0 = {}
>>> alien_0['color'] = 'green'
>>> alien_0['points'] = 5
>>> print(alien_0)
{'color': 'green', 'points': 5}
2.5 修改字典中的值
- 修改字典中的值,依次指定字典名、方括号括起的键、相关联的新值
alien_0 ={'color':'green'}
print("The alien is "+alien_0['color']+".")
alien_0['color'] = 'yellow'
print("The alien is now "+alien_0['color']+".")
The alien is green.
The alien is now yellow.
- 有趣例子
alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
alien_0['speed'] = 'fast'
print("Original x-position: " + str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position']=alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
Original x-position: 0
New x-position: 3
2.6 由类似对象组成的字典
- 前面示例中,字典存储的是一个对象的多种信息;也可以使用字典来存储众多对象的同一种信息
- 定义好字典后,在最后一个键—值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐
- 可在最后一个键—值对后面也加上逗号,为以后在下一行添加键—值对做好准备
- print语句后续各行,用tab键将它们对齐并缩进一级,在最后一行末尾加上右括号
>>> favorite_languages = {
... 'jen':'python',
... 'sarah':'c',
... 'edward':'ruby',
... 'phil':'pyrhon',
... }
>>> print("Sarah's favorite language is "+
... favorite_languages['sarah'].title()+
... ".")
Sarah's favorite language is C.
3. 遍历字典
3.1 遍历所有键—值对
- 列表名.items()
- 方法items()返回一个键—值对列表
- 遍历字典时,键—值对的返回顺序也与存储顺序不同;Python不关心键—值对的返回顺序,它只跟踪键和值之间的关联关系
>>> user_0 = {
... 'username':'efermi',
... 'first':'enrico',
... 'last':'fermi',
... }
>>> for key ,value in user_0.items():
... print("\nkey: "+key)
... print("Value: "+value)
...
key: username
Value: efermi
key: first
Value: enrico
key: last
Value: fermi
>>> favorite_languages = {
... 'jen':'python',
... 'sarah':'c',
... 'edward':'ruby',
... 'phil':'pyrhon',
... }
>>> for name,language in favorite_languages.items():
... print(name.title() + "'s favorite language is "+
... language.title() + ".")
...
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Pyrhon.
3.2 遍历所有键
- 列表名.keys()
- 方法keys()返回一个包含字典中的所有键的列表
- 遍历字典时,会默认遍历所有的键,下面两种写法均可
for name in favorite_languages.keys():
for name in favorite_languages:
- 演示操作1:
>>> favorite_languages = {
... 'jen': 'python',
... 'sarah': 'c',
... 'edward': 'ruby',
... 'phil': 'pyrhon',
... }
>>> for name in favorite_languages.keys():
... print(name.title())
...
Jen
Sarah
Edward
Phil
- 演示操作2:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'pyrhon',
}
friends = ['phil','sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
if 'erin' not in favorite_languages.keys():
print("Erin,please take our poll!")
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Pyrhon!
Erin,please take our poll!
3.3 遍历所有值
- 遍历所有(未去重)
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
The following languages have been mentioned:
Python
C
Ruby
Python
- 遍历所有,剔除重复值(使用集合set)
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
The following languages have been mentioned:
C
Python
Ruby
3.4 顺序遍历
3.4.1 顺序遍历键—值对
- 实际上还是以键来排序
>>> user_0 = {
... 'username':'efermi',
... 'first':'enrico',
... 'last':'fermi',
... }
>>> for key ,value in sorted(user_0.items()):
... print("\nkey: "+key)
... print("Value: "+value)
...
key: first
Value: enrico
key: last
Value: fermi
key: username
Value: efermi
3.4.2 顺序遍历键
>>> favorite_languages = {
... 'jen': 'python',
... 'sarah': 'c',
... 'edward': 'ruby',
... 'phil': 'pyrhon',
... }
>>> for name in sorted(favorite_languages.keys()):
... print(name.title())
...
Edward
Jen
Phil
Sarah
3.4.3 顺序遍历值
- 顺序遍历值—未去重
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mentioned:")
for language in sorted(favorite_languages.values()):
print(language.title())
The following languages have been mentioned:
C
Python
Python
Ruby
- 顺序遍历值—去重
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mentioned:")
for language in sorted(set(favorite_languages.values())):
print(language.title())
The following languages have been mentioned:
C
Python
Ruby
4. 嵌套
4.1 列表中嵌套字典
- 演示操作
>>> alien_0 = {'color':'green','points':5}
>>> alien_1 = {'color':'yellow','points':10}
>>> alien_2 = {'color':'red','points':15}
>>> aliens = [alien_0,alien_1,alien_2]
>>> for alien in aliens:
... print(alien)
...
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
- 有趣的例子
aliens = []
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
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
for alien in aliens[0:5]:
print(alien)
print("...")
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
4.2 字典中嵌套列表
- 每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表
- 演示操作1:
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
print("You ordered a " + pizza['crust'] + "-crust pizza" +
" with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
- 演示操作2:
>>> favorite_languages = {
... 'jen': ['python','ruby'],
... 'sarah': ['c'],
... 'edward': ['ruby','go'],
... 'phil':['python','haskell'],
... }
>>> for name ,languages in favorite_languages.items():
... if len(languages) == 1:
... for language in languages:
... print("\n" + name.title() + " 's favorite language is: " + language.title())
... elif len(languages) > 1:
... print("\n" + name.title() + " 's favorite languages are:")
... for language in languages:
... print("\t" + language.title())
...
Jen 's favorite languages are:
Python
Ruby
Sarah 's favorite language is: C
Edward 's favorite languages are:
Ruby
Go
Phil 's favorite languages are:
Python
Haskell
4.3 字典中嵌套字典
>>> users = {
... 'aeinstein':{
... '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: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris