字典
在Python中,字典 字典 是一系列键 键—值对 值对 。每个键 键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将 任何Python对象用作字典中的值。
单纯的字典
在Python中,字典用放在花括号{} 中的一系列键—值对表示
alien_0 = {'color': 'green', 'points': 5}
访问字典中的值
alien_0 = {'color': 'green'}
print(alien_0['color'])
> green
添加键值对
字典是种动态结构,可以任意添加键值对
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}
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5 print(alien_0)
print(alien_0)
> {'color': 'green', 'points': 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.
删除键值对
del(key)语句删除键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
> {'color': 'green', 'points': 5}
> {'color': 'green'}
遍历字典
同样是用for循环遍历字典
遍历字典中的key
可以用.keys()也可以省略
demo1:
user = {
'user_0': 'bob',
'user_1': 'nike',
'user_2': 'john'
}
for key in user:
print(key)
>
user_0
user_1
user_2
demo2:
user = {
'user_0': 'bob',
'user_1': 'nike',
'user_2': 'john'
}
for key in user.keys():
print(key)
>
user_0
user_1
user_2
用items()来遍历键和值
user = {
'user_0': 'bob',
'user_1': 'nike',
'user_2': 'john'
}
for key, value in user.items():
print(key)
print(value)
>
user_0
bob
user_1
nike
user_2
john
遍历字典中的值
demo1:
用items()可以遍历整个字典,也可以单独遍历值
user = {
'user_0': 'bob',
'user_1': 'nike',
'user_2': 'john'
}
for key, value in user.items():
print(value)
>
bob
nike
john
demo2:
可以用values()方法
user = {
'user_0': 'bob',
'user_1': 'nike',
'user_2': 'john'
}
for value in user.values():
print(value)
>
bob
nike
john
嵌套
字典列表
demo1:
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}
demo2:
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
yellow
red
在字典中储存字典
demo1:
school = {
'class1': {
'student1': 'bob',
'student2': 'mosh',
'student3': 'mike'
},
'class2': {
'student1': 'john',
'student2': 'dive',
'student3': 'pip'
}
}
for classes, students in school.items():
print(classes)
print(':')
print(students)
>
class1
:
{'student1': 'bob', 'student2': 'mosh', 'student3': 'mike'}
class2
:
{'student1': 'john', 'student2': 'dive', 'student3': 'pip'}
demo2:
school = {
'class1': {
'student1': 'bob',
'student2': 'mosh',
'student3': 'mike'
},
'class2': {
'student1': 'john',
'student2': 'dive',
'student3': 'pip'
}
}
for students in school.values():
students['student1'] = 'dadaa'