目录
-
字典的定义
1、Python内置的数据结构之一,与列表一样是一个可变序列(int、str是不可变序列)(列表、字典是可变序列)
2、以键值对的方式储存数据,字典是一个无序的序列
键所在位置由hash函数计算决定,故放在字典中的键是不可变序列(不可以进行增删改)
3、实现原理:与查字典类似,先根据部首或拼音找汉字对应页码,Python中字典先根据key查找value所在的位置
4、字典的特点
(列表不会浪费太大内存,因为只储存索引,值是用指针指过去的,是时间换空间的数据结构)
-
字典的创建
最常用花括号:scores={ ‘张三’:100,‘李四’:98,‘王五’:45}
使用内置函数dict():dict(name=‘jack’,age=20)
#创建字典
scores={'a':100,'b':'c','d':600}
print(scores,type(scores))
student=dict(name='jack',age=20,weight=60)
print(student)
#空字典
d={}
print(d)
-
字典的查询操作
1、字典元素的获取
【】取值与使用get()取值的区别:
[]如果字典中不存在指定的key,抛出keyError异常
get()方法取值,如果字典中不存在指定的 key,并不会抛出KeyError而是返回 None,可以通过参数设置默认的value,以便指定的key不存在时返回设置的value
scores={'a':100,'b':'c','d':600}
print(scores['a'])
#print(scores['w'])#KeyError: 'w'
print(scores.get('a'))
print(scores.get('w'))#None
print(scores.get('f',99))#通过参数设置默认的value,键f不存在,返回99,如果键不存在,返回键f的值
2、key的判断
scores={'a':100,'b':'c','d':600}
print('a' in scores)#True
print('a' not in scores)#False
3、获取字典的视图
scores={'a':100,'b':'c','d':600,'f':80}
k=scores.keys()#获取所有的键
print(k,type(k))
print(list(k))#将所有键组成的视图转为列表
v=scores.values()#获取所有的值
print(v,type(v))
print(list(v))#将所有值组成的视图转为列表
i=scores.items()##获取所有的键值对
print(i,type(i))#元组
print(list(i))#将所有键值对组成的视图转为列表,包含四个元素,每一个元素为一组元组()
4、字典元素的遍历
for 迭代变量 in 字典名 :
for item in scores:
print(item,end='\t')#遍历字典中的键
print()
for item in scores:
print(item,scores[item],end='\t')#遍历字典中的键和值
-
字典元素的增删改操作
1、字典元素的删除
del scores['a']#删除指定的键值对(key-value对)
print(scores)
scores.clear()#清空字典中所有元素
print(scores)
2、字典元素的新增与修改
scores={'a':100,'b':'c','d':600}
scores['f']=90#新增元素
print(scores)
scores['f']=80#修改元素
print(scores)
-
字典生成式
生成字典
内置函数zip():用于将可迭代对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表
items=['Fruites','Books','Others']
prices=[96,78,85]
d={item.upper():price for item,price in zip(items,prices)}#如果两个列表的元素字数不一样,以元素字数少的为准
#upper()是将小写变为大写的函数
print(d)