第七章 字典 { }
57. 什么是字典
(1)Python内置的数据结构之一,与列表一样是一个可变序列
(2)以键值对的方式存储数据,字典是一个无序的序列(列表——有序)
(3)字典: sorces ={ ‘张三’ :100 , ‘李四’ :98 , ‘王五’ :45}
hash(key) —— 不可变序列(不可执行增、删、改操作) —— e.g. 整数序列,字符串str序列
可变序列—— 列表,字典
58. 字典的实现原理
字典的实现原理与查字典一样,查字典是先根据部首或拼音查找汉字对应的页码,Python中的字典是根据key查找value所在的位置。—— hash(key)
59. 字典的创建
(1)最常见的方式:使用花括号
(2)使用内置函数dict()
(3)空字典
print('------------------59.字典的创建--------------------')
print('最常见的方式:使用花括号{}')
scores={'张三':100,'李四':98,'王五':45}
print(scores,type(scores))
print('使用内置函数dict()')
student=dict(name='jack',age=20)
print(student)
print('空字典')
d={}
print(d)
60. 字典元素的获取
获取字典中的元素 | ① [ ] —— scores[‘张三’] | 两种方法的区别 (1)[ ]如果字典中不存在指定的key,抛出keyError异常 (2)get( )方法取值,如果字典中不存在指定的key,并不会抛出keyError而是返回None。可以通过参数设置默认的Value,以指定的key不存在时返回 |
②get()方法—— scores.get(‘张三’) |
print('------------------60.字典元素的获取--------------------')
print('方法一:[]')
print(scores['张三'])
#print(scores['美女']) 返回 KeyError:
print('方法二:get()')
print(scores.get('张三'))
print(scores.get('帅哥')) #None
print(scores.get('麻七',118)) #118是在查找‘麻七’所对应的value不存在时,提供的一个默认值
61. 字典元素的增、删、改操作
(1)key的判断
① in —— 指定的key在字典中存在返回True —— ‘张三’ in scores
② not in —— 指定的key在字典中不存在返回False —— ‘Mary’ not in scores
(2)字典元素的删除
del scores[‘张三’] —— 删除指定的键值对(key-value)
scores.clear() —— 清空字典的元素
(3)字典元素的新增 / 修改
scores[‘Jack’]=90
print('------------------61.字典元素的增、删、改操作--------------------')
scores={'张三':100,'李四':98,'王五':45}
print('(1)key的判断')
print('张三' in scores)
print('张三' not in scores)
print('(2)字典元素的删除')
del scores['张三']
print(scores)
scores.clear() # 清空字典元素
print(scores)
print('(3)字典元素的新增')
scores={'张三':100,'李四':98,'王五':45}
scores['happy']=98 #新增元素
print(scores)
scores['happy']=66 #修改元素
print(scores)
62. 获取字典视图
(1)keys() —— 获取字典中所有key
(2)values() —— 获取字典中所有value
(3)items() —— 获取字典中所有 key-value 对
print('-------------------------62.获取字典视图--------------------------')
print('(1)获取字典中所有key ')
keys=scores.keys()
print(keys)
print(type(keys))
print(list(keys)) #将所有key组成的视图转成列表
print()
print('(2)获取字典中所有value ')
values=scores.values()
print(values,type(values))
print(list(values))
print()
print('3.获取字典中所有 key-value 对')
items=scores.items()
print(items,type(items))
print(list(items)) #转换之后的列表元素由元组组成 (元组见第八章)
63. 字典元素的遍历
for item in scores:
print(item)
print('---------------------63.字典元素的遍历-----------------------')
for i in scores:
print(i)
print(i,scores[i])
print(i,scores.get(i))
64. 字典的特点
(1)字典中的所有元素都是一个key-value 对,key不允许重复,value可以重复(否则值将被覆盖)
(2)字典中的元素是无序的 (无法手动指定位置进行操作)
(3)字典中的key必须是不可变对象
(4)字典也可以根据需要动态地伸缩(使用前不需要分配空间)
(5)字典会浪费较大的内存,是一种使用空间换时间的数据结构(浪费空间但查找速度快)
65. 字典生成式
(1)内置函数 zip()
用于将可迭代的对象(使用for in 循环进行遍历的对象)作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表
print('---------------------65.字典生成式-----------------------')
items=['Fruit','Books','Others']
price=[96,78,85]
d={item:price for item, price in zip(items,price)}
print(d)
d={item.upper():price for item, price in zip(items,price)}
# item.upper --> 所有字母均改成大写
print(d)
a={'d','s','a'}
b={12}
c={a:b for a,b in zip(a,b)}
print(c)