字典:python内置的数据结构之一,与列表一样是一个可变序列。以键值对的方式存储数据,字典是一个无序的序列。例:scores={ '张三': 100, '李四' :98, '王五': 45}
字典的实现原理:字典的实现原理与查字典类似,查字典是先根据部首或拼音查找相应的页码,Python中的字典是根据key查找value所在的位置
字典的创建
最常用的方式:使用花括号
scores={ '张三': 100, '李四' :98, '王五': 45}
使用内置函数dict()
dict(name='jack' ,age=20)
'''字典的创建方式'''
'''使用{}创建字典'''
scores={ '张三': 100, '李四' :98, '王五': 45}
print(scores)#{'张三': 100, '李四': 98, '王五': 45}
print(type(scores))#<class 'dict'>
'''第二种创建dict()'''
student=dict(name='jack',age=20)
print(student)#{'name': 'jack', 'age': 20}
'''空字典'''
d={}
print(d)#{}
字典中元素的获取
1、[] --------举例:scores['张三']
2、get()方法--------举例:scores.get('张三')
[]取值和使用get()取值的区别
1、[]如果字典中不存在指定的key,抛出keyError异常。
2、get()方法取值,如果字典中不存在指定的key,并不会抛出keyError而是返回None,可以通过参数设置默认的value,以便指定的key不存在时返回。
'''字典的创建方式'''
'''使用{}创建字典'''
scores={ '张三': 100, '李四' :98, '王五': 45}
print(scores)#{'张三': 100, '李四': 98, '王五': 45}
print(scores['张三'])#100
print(scores.get('张三'))#100
#print(scores['ss'])#KeyError: 'ss'
print(scores.get('ss'))#None
print(scores.get('陈留',99))#99 99是在查找陈留所对的value不存在时,提供的一个默认值
key的判断
in-----指定的key在字典中存在返回True
not in -----指定的key在字典中不存在返回True
字典元素的删除
del scores['张三']
字典元素的新增
scores['Jack']=90
scores={ '张三': 100, '李四' :98, '王五': 45}
del scores['张三']
print(scores)#{'李四': 98, '王五': 45}
scores.clear()
print(scores)#{}
scores['陈六']=98
print(scores)#{'陈六': 98}
scores['陈六']=100
print(scores)#{'陈六': 100}
获取字典视图的三个方法
1、keys()--------获取字典中所有key
2、values()--------获取字典中所有value
3、items()----------获取字典中所有key,value对
scores={ '张三': 100, '李四' :98, '王五': 45}
keys=scores.keys()
print(keys)#dict_keys(['张三', '李四', '王五'])
print(type(keys))#<class 'dict_keys'>
print(list(keys))#['张三', '李四', '王五']
values=scores.values()
print(values)#dict_values([100, 98, 45])
print(type(values))#<class 'dict_values'>
print(list(values))#[100, 98, 45]
item=scores.items()
print(item)#dict_items([('张三', 100), ('李四', 98), ('王五', 45)])
print(type(item))#<class 'dict_items'>
print(list(item))#[('张三', 100), ('李四', 98), ('王五', 45)] 转换之后的列表元素是由元组成的
字典元素的遍历:
for item in scores :
print(item)
字典的特点
1、字典中的所有元素都是一个key-value对,key不允许重复,value可以重复
2、字典中的元素是无序的
3、字典中的key必须是不可变对象
4、字典也可以根据需要动态的伸缩
5、字典会浪费较大的内存,是一种使用空间换时间的数据结构
字典生成式
内置函数zip()
用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表
items=['Fruits','Books','Others'] prices=[96,78,85] lst=zip(items,prices) print(list(lst)) |
字典表达式: { item.upper() :price for item,price in zip(item,prices)}
这里item.upper()表示字典key的表达式 第一个price表示字典value的表达式 item是自定义表示key的变量 第二个price自定义表示value的变量 zip(items,prices)表示可迭代对象
items=['Fruits','Books','Others']
prices=[96,78,85]
d={item.upper():price for item ,price in zip (items,prices)}#这里的upper()是大写操作
print(d)#{'Fruits': 96, 'Books': 78, 'Others': 85}