第 六 章 字典
区别: 列表 :方括号,元组:圆括号,字典:花括号
字典 是一系列键、值对,每个键 都与一个值相关联。
可以使用键来访问与之相关联的值,与键相关联的值可以是数字、字符串、列表乃至字典。
6.2.1 访问字典中的值
alien_0 = {‘color’: ‘green’} #'color’为键, 'green’为值
print(alien_0[‘color’])
6.2.2 添加键—值对
先指定字典,然后将键用方括号括起来,并对于相关联的值
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0)
alien_0[‘x_position’] = 0
alien_0[‘y_position’] = 25
print(alien_0)
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5, ‘y_position’: 25, ‘x_position’: 0} #顺序与添加顺序不同
6.2.3 先创建一个空字典
alien_0 = {}
alien_0[‘color’] = ‘green’
alien_0[‘points’] = 5
print(alien_0)
{‘color’: ‘green’, ‘points’: 5}
6.2.4 修改字典中的值
和添加类似
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.
6.2.5 删除键—值对
使用del 语句将相应的键—值对彻底删除
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0)
del alien_0[‘points’]
print(alien_0)
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’}
6.2.6 由类似对象组成的字典
favorite_languages = { # 人名和他喜欢的语言
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
print("Sarah’s favorite language is " +
favorite_languages[‘sarah’].title() +
“.”)
Sarah s favorite language is C.
6.3 遍历字典
user_0 = {
‘username’: ‘efermi’,
‘first’: ‘enrico’,
‘last’: ‘fermi’,
}
for key, value in user_0.items(): #key, value可以换成任意两个字符变量
print("\nKey: " + key)
print("Value: " + value)
Key: last
Value: fermi
Key: first
Value: enrico
Key: username
Value: efermi
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() + “.”)
Phils favorite language is Python.
Phils favorite language is Python.
Phils favorite language is Python.
Phils favorite language is Python.
6.3.2 遍历字典中的所有键
for name in favorite_languages.keys(): #keys()可以省略
print(name.title())
6.3.3 按顺序遍历字典中的所有键
使用函数sorted() 来获得按特定顺序排列的键列表的副本
for name in sorted(favorite_languages.keys()):
print(name.title() + “, thank you for taking the poll.”)
6.3.4 遍历字典中的所有值
for language in favorite_languages.values(): # 可使用set(favorite_languages.values() 剔除重复的值
print(language.title())
6.4 嵌套
6.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}
6.4.2 在字典中存储列表
pizza = {
‘crust’: ‘thick’,
‘toppings’: [‘mushrooms’, ‘extra cheese’],
}
6.4.3 在字典中存储字典
users = {
‘aeinstein’: {
‘first’: ‘albert’,
‘last’: ‘einstein’,
‘location’: ‘princeton’,
},
‘mcurie’: {
‘first’: ‘marie’,
‘last’: ‘curie’,
‘location’: ‘paris’,
},
}