1.字典与列表的区别
a.列表以[ ]定义,字典以{ }定义
b.列表的一个元素就是一个元素,而字典是以键值对存储
c.列表是有序的,字典是无序的
字典的示意图:
2.可变序列和不可变序列
字符串是不可变序列,如a=‘hello’,表示a指向了一个存储‘hello’的内存空间,当我想改为‘hello,world’时,我写了代码:a=‘hello,world’,但在内存中并非是在‘hello’的内存空间中修改成‘hello,world’,而是重新开辟了一个内存空间,里面是‘hello,world’,a转而指向了他,整个过程中‘hello’并没有改变,所以说字符串是不可变序列。
目前学到的列表,字典都是可变序列,修改则直接在指定内存空间内修改,不会开辟新的内存空间来存储。
3.字典的创建
#第一种
scores={'张三':100,'李四':98,'王五':45}
print(scores)
#第二种
student=dict(张三=100,李四=98,王五=45)
print(student)
#空字典
d={}
4.元素的获取
scores={'张三':100,'李四':98,'王五':45}
#法1
print(scores['张三']) #100
print(scores['李六']) #报错
#法2
print(scores.get('张三')) #100
print(scores.get('李六')) #None
print(scores.get('李六','没有')) #第二个空指定了找不到时返回的默认值
5.键的判断
scores={'张三':100,'李四':98,'王五':45}
print('张三' in scores)
print('张三' not in scores)
6.删除与增加
scores={'张三':100,'李四':98,'王五':45}
del scores['张三'] #删除指定的键值对
print(scores) #{'李四':98,'王五':45}
scores.clear() #清空
print(scores) #{}
scores={'张三':100,'李四':98,'王五':45}
scores['陈六']=120
print(scores) #{'张三':100,'李四':98,'王五':45,'陈六':120}
7.获取字典视图
scores={'张三':100,'李四':98,'王五':45}
# 获取所有的key
keys = scores.keys()
print(keys, type(keys)) #dict_keys(['张三', '李四', '王五']) <class 'dict_keys'>
# 获取所有的value
values = scores.values()
print(values, type(values)) #dict_values([100, 98, 45]) <class 'dict_values'>
# 获取所有的 key-value
item = scores.items()
print(item, type(item))
#dict_items([('张三', 100), ('李四', 98), ('王五', 45)]) <class 'dict_items'>
8.字典元素的遍历
scores = {'张三': 100, '李四': 98, '王五': 45}
# 字典元素遍历
for item in scores:
print(item, scores[item], scores.get(item))
'''
张三 100 100
李四 98 98
王五 45 45
'''
9.特点
# key不能重复,value可重复
student = {'张三': 100, '张三': 120}
print(student) #{'张三': 120}
student1 = {'张三': 100, '李四': 100}
print(student1) #{'张三': 100, '李四': 100}
# 无序,不能在指定位置插入元素
# key必须是不可变对象
# 根据需要动态伸缩
# 字典浪费较大内存,空间换取时间
10.字典生成式
# 内置函数zip(),将可迭代对象对应元素打包成元组,然后返回成元组构成的列表
items = ['Fruits', 'Books', 'Others']
prices = [96, 78, 85]
lst = zip(items, prices) # type是zip
d = {item.upper(): price for item, price in lst}
print(d)
#{'FRUITS': 96, 'BOOKS': 78, 'OTHERS': 85}
'''
upper()字符串大写转换函数,lower()字符串小写转换函数
'''
print('Hello'.upper()) # HELLO
print('Hello'.lower()) # hello