字典
字典是python内置的数据库之一,与列表类似,是可变序列。
字典是以键值对的方式存储数据,字典是一个无序系列。
字典是实现原理:与查字典类似,先根据部首或拼音查找对应页码,python中的字典是根据key查找value所在的位置。
字典的创建与删除
常见方式花括号:{}
使用内置函数:dict( )
scores1 = {'peter':98,'sushan':76,'tom':86}
scores2 = dict(name='peter',score=86)
scores3 ={} #创建空字典
scores4 ={}
print(type(scores1),id(scores1))
print(type(scores2),id(scores2))
print(type(scores3),id(scores3))
print(type(scores4),id(scores4)) #四个字典id都不一样
字典的查询与操作
有两种方式:dict[] 或 get() 内置函数
scores1 = {'peter':98,'sushan':76,'tom':86}
print(scores1['peter'])
#print(scores1['ann']) #ann不存在会报错
print(scores1.get('peter'))
print(scores1.get('ann')) ann不存在,返回None
print('peter' in scores1) #判断key是否在dict内,返回True
字典元素的增、删、改及视图操作
scores1 = {'peter':98,'sushan':76,'tom':86}
del scores1['peter'] #删除指定的键值对
print(scores1)
scores1.clear() #清空字典中的元素,变成空字典
print(scores1)
scores1['ann']=100 #修改空字典为一个元素
print(scores1)
scores1 = {'peter':98,'sushan':76,'tom':86} #直接赋值,修改空字典
scores1['peter']=56 #修改某个key的值
print(scores1)
name=scores1.keys() #获取key及数据类型
print(name,type(name))
score=scores1.values() #获取value及数据类型
print(score,type(score))
print(list(name)) #转化为列表
print(list(score))
{'sushan': 76, 'tom': 86}
{}
{'ann': 100}
{'peter': 56, 'sushan': 76, 'tom': 86}
dict_keys(['peter', 'sushan', 'tom']) <class 'dict_keys'>
dict_values([56, 76, 86]) <class 'dict_values'>
['peter', 'sushan', 'tom']
[56, 76, 86]
字典元素的遍历
scores1 = {'peter':98,'sushan':76,'tom':86}
for i in scores1:
print(i,scores1[i],scores1.get(i)) #两种获取字典value的方式
peter 98 98
sushan 76 76
tom 86 86
字典的特点:
- 字典的所有元素都是一个键值对,key不允许重复,value可以重复
- 字典中的key必须是不可变量
- 字典也可以根据需要动态的伸缩
- 字典会浪费较大的内存,是一种使用空间换时间的数控结构
Name={'name':'zhangsan','name':'lisi'} #keys不能重复,但是不提示错误。
print(Name)
{'name': 'lisi'}
字典生成式
内置函数zip():用于将可迭代对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元素组成的列表
items =['fruits','books','others']
prices = [96,156,23,100] #元素个数不一样,以元素少的为基准
d={items:prices for items,prices in zip(items,prices)}
print(d)
{'fruits': 96, 'books': 156, 'others': 23}
总结:子弹创建三种方式有{},内置函数dict(),内置函数zip()