Python内置了字典(使用花括号{}表示):dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值对(key-value)存储,每个键与一个值相关联,具有极快的查找速度。
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
print(students['Michael'])
可以把键(key)当作索引。
- 一个key只能对应一个value
多次对一个key放入value,后面的值会把前面的值替换掉
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
print(students['Michael'])
#修改Michael 的 value
students['Michael'] = 201
print(students['Michael'])
- 添加键-值对
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
#键为Judy和Divid,值为105和107
students['Judy'] = 105
students['Divid'] = 107
print(students)
输出>>>{'Michael': 201, 'Lily': 102, 'Tom': 103, 'Judy': 105, 'Divid': 107}
Python不关心键值对的添加顺序,只关心它们的关联关系。
- 删除键-值对
对于字典中不再需要的信息,使用del语句将键-值对彻底删除。使用del语句时,必须指定字典名和要删除的键。
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
del students['Tom']
print(students)
输出>>>{'Michael': 101, 'Lily': 102}
- 遍历字典
1.遍历键-值对
使用方法items()
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
for name, num in students.items():
print("\nStudent_Name:", name)
print("Student_Num", num)
2.遍历键
使用方法keys()
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
for name in students.keys():
print("\nStudent_Name:", name)
3.遍历值
使用方法values()
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
for num in students.values():
print("\nStudent_Num:", num)
- 去重
使用set(),找出列表中独一无二的元素,并创建新的集合。
#新增一个值为101的键值对
students = {'Michael': 101, 'Lily': 102, 'Tom': 103, 'Kiven': 101}
for num in set(students.values()):
print(num)
输出>>>101
>>>102
>>>103
- 字典嵌套
字典储存在列表中,或者列表储存在字典中
#新增一个teachers字典,并保存在school列表中
students = {'Michael': 101, 'Lily': 102, 'Tom': 103}
teachers = {'Math': 901, 'English': 905, 'Art': 908}
school = [students, teachers]
for person in school:
print(person)
dict和list比较,有以下几个特点:
查找和插入的速度极快,不会随着key的增加而变慢;
需要占用大量的内存,内存浪费多。
而list相反:
查找和插入的时间随着元素的增加而增加;
占用空间小,浪费内存很少。
所以,dict是用空间来换取时间的一种方法。