字典是python中独特的一种数据结构:
他是Python内置的数据结构之一,与列表一样是一个可变序列
以键值对的方式存储数据,字典是一个无序的序列
字典的实现原理与查字典类似,查字典是先根据部首或拼音查找汉字对应的页码,Python中的字典是根据key查找value所在的位置
它具有查找效率高的优点
这篇文章是我对于字典知识点的总结。
一、字典的创建方式
'''使用{}创建字典'''
scores={'张三':100,'李四':98,'王五':45}
print(scores)
print(type(scores))
'''第二种创建dict()'''
student=dict(name='jack',age=20)
print(student)
'''空字典'''
d={}
print(d)
二、获取字典中的值:
可以通过输入键,然后可以获得值:
scores={'张三':100,'李四':98,'王五':45}
'''第一种方式,使用[]'''
print(scores['张三'])
#print(scores['陈六']) #KeyError: '陈六'
'''第二种方式,使用get()方法'''
print(scores.get('张三'))
print(scores.get('陈六')) #None
print(scores.get('麻七',99)) #99是在查找'麻七'所对的value不存在时,提供的一个默认值
因为第一种会报错,第二种会输出默认值,所以第二种方式会有更大的灵活性。
三、键的判断:
scores={'张三':100,'李四':98,'王五':45}
print('张三' in scores)
print('张三' not in scores)
四、键的删除:
del
del scores['张三'] #删除指定的key-value对
#scores.clear() #清空字典的元素
五、键的增加:
scores['陈六']=98 #新增元素
六、键的修改:
scores['陈六']=100 #修改元素
七、获取字典的视图:
scores={'张三':100,'李四':98,'王五':45}
#获取所有的key
keys=scores.keys()
print(keys)
print(type(keys))
print(list(keys)) #将所有的key组成的视图转成列表
#获取所有的value
values=scores.values()
print(values)
print(type(values))
print(list(values))
#获取所有的key-value对
items=scores.items()
print(items)
print(list(items)) #转换之后的列表元素是由元组组成
八、字典元素的遍历:
scores={'张三':100,'李四':98,'王五':45}
#字典元素的遍历
for item in scores:
print(item,scores[item],scores.get(item))
九、字典生成式:
zip打包
items=['Fruits','Books','Others']
prices=[96,78,85,100,120]
d={item.upper():price for item ,price in zip(items,prices) }
print(d)