字典定义
people = {'name':'lily','sex':'man'}
print(people['name'])
print(people['sex'])
---ans---
lily
man
键-值对使两个相关联的值。键和值之间用冒号分割,而键-值对之间用逗号分隔。
在空字典中可以存储任意数量的键-值对。
访问、添加与删除
访问
people = {'name':'lily','sex':'man'}
print(people['name'])
---ans---
lily
指定字典名以及方括号内的键,来进行访问。
添加
字典是一种动态结构,可随时添加键-值对。
people = {'name':'lily','sex':'man'}
people['grade'] = 'four'
print(people)
---ans---
{'name': 'lily', 'sex': 'man', 'grade': 'four'}
直接添加
删除
使用del语句将相应的键-值对彻底删除。
people = {'name':'lily','sex':'man'}
people['grade'] = 'four'
print(people)
del people['grade']
print(people)
---ans---
{'name': 'lily', 'sex': 'man', 'grade': 'four'}
{'name': 'lily', 'sex': 'man'}
遍历字典
遍历所有的键-值对
people = {'name':'lily','sex':'man','grade':'four'}
print(people)
for key, value in people.items():
print("\nKey: "+key)
print("Value: "+value)
---ans---
Key: name
Value: lily
Key: sex
Value: man
Key: grade
Value: four
items()
方法,返回一个键-值队列表。
for遍历,将每个键-值对存储到指定的两个变量中,来进行操作。
遍历所有键
people = {'name':'lily','sex':'man','grade':'four'}
for key in people.keys():
print("Key: "+key)
---ans---
Key: name
Key: sex
Key: grade
keys()
方法,获取字典中的键列表。
for循环,可以对每一次遍历获得的键再次使用。这里键的值,也就是字符串str
类型。
实验
Key: name
<class 'str'>
Key: sex
<class 'str'>
Key: grade
<class 'str'>
顺序遍历字典中的所有键
people = {'name':'lily','sex':'man','grade':'four'}
for key in sorted(people.keys()):
print("Key: "+key)
---ans---
Key: grade
Key: name
Key: sex
由于字典只是记录键与值之间的映射关系,字典中元素的排列顺序未知,要想有效获得顺序遍历的字典值,需要对字典中的元素进行处理。
使用sorted()
方法,来获得特定顺序排列的键列表的副本。
顺序遍历字典中的所有值
people = {'name':'lily','sex':'man','grade':'four'}
for key in sorted(people.values()):
print("Values: "+key)
---ans---
Values: four
Values: lily
Values: man
使用values()
方法,来获得一个值列表。
获得独一无二的值
people = {'name':'lily','sex':'man','grade':'four','age':'four'}
for key in set(people.values()):
print("Values: "+key)
---ans---
Values: lily
Values: four
Values: man
使用set()
方法,来获得唯一的元素列表。
在这里使用set()
,获得唯一的字典值列表,该列表中的元素唯一,且不重复。
嵌套
列表里面包含字典
people1 = {'name':'lily','sex':'man'}
people2 = {'name':'red','sex':'women'}
people3 = {'name':'bob','sex':'man'}
persons = [people1, people2, people3]
for item in persons:
print(item)
---ans---
{'name': 'lily', 'sex': 'man'}
{'name': 'red', 'sex': 'women'}
{'name': 'bob', 'sex': 'man'}
字典里面包含列表
classes = ['chinese', 'english', 'math']
student = {'name':'lily','sex':'man', 'pclass':classes}
for item in student['pclass']:
print(item)
---ans---
chinese
english
math
先创建一个列表,存储相关信息。
再可以将列表变量,通过键-值对的形式添加到设置的字典中。在访问的过程中,通过对字典相应键的访问,实现对该列表的访问和操作。
字典中包含字典
english_class = {'time':'8pm', 'place':'b2', 'teacher':'bob'}
student = {'name':'lily','sex':'man', 'eng_class':english_class}
for key in student.keys():
if key == 'eng_class':
for value in student[key].values():
print(value)
---ans---
8pm
b2
bob
先创建一个字典变量a,然后创建一个新的字典变量b。可以将字典变量a添加到字典变量b中,然后通过字典的访问和操作机制来对字典变量b中的字典变量a进行访问与操作。