# -*- coding: utf-8 -*-
# @Time : 2021/9/27 10:31
# @Author : 李新宇
# @FileName: demo1.py
# @Software: PyCharm
'''字典的创建方式'''
'''使用{}创建字典'''
scores={'张三':100,'李四':20,'王五':30}
print(scores)
'''第二种创建dict()'''
student=dict(name='Eden',age=20)
print(student)
'''创建空字典'''
d={}
print(d)
# -*- coding: utf-8 -*-
# @Time : 2021/9/27 10:46
# @Author : 李新宇
# @FileName: demo2.py
# @Software: PyCharm
'''获取字典的元素'''
scores={'张三':100,'李四':20,'王五':30}
'''第一种方式,使用[]'''
print(scores['张三'])
#print(scores['陈六'])#KeyError: '陈六'
'''第二种,使用get()方法'''
print(scores.get('张三'))
#print(scores.get('陈六')) #None
print(scores.get('麻七','查找不存在'))#查找不存在返回逗号后的默认值
# -*- coding: utf-8 -*-
# @Time : 2021/9/27 10:52
# @Author : 李新宇
# @FileName: demo3.py
# @Software: PyCharm
scores={'张三':100,'李四':20,'王五':30}
print('张三' in scores) #True
print('张三' not in scores) #False
del scores['张三'] #删除指定键值对
print(scores)
# scores.clear() #清空字典中的元素
# print(scores)
scores['陈六']=98 #新增元素
print(scores)
scores['陈六']=100 #修改元素
print(scores)
# -*- coding: utf-8 -*-
# @Time : 2021/9/27 10:57
# @Author : 李新宇
# @FileName: demo4.py
# @Software: PyCharm
scores={'张三':100,'李四':20,'王五':30}
#获取所有的key
keys=scores.keys()
print(keys)
print(type(keys))
print(list(keys)) #将所有键组成的视图组成列表
#获取的所有value
values=scores.values()
print(values)
print(type(values))
print(list(values))
#获取所有的键值对
print('------')
items=scores.items()
print(items)
print(list(items)) #转换之后的列表元素是由元组()组成,下个章节讲解
# -*- coding: utf-8 -*-
# @Time : 2021/9/27 11:06
# @Author : 李新宇
# @FileName: demo5.py
# @Software: PyCharm
scores={'张三':100,'李四':20,'王五':30}
#字典元素的遍历
for item in scores:
print(item,scores[item],scores.get(item)) #输出键,输出值,输出值
# -*- coding: utf-8 -*-
# @Time : 2021/9/27 11:10
# @Author : 李新宇
# @FileName: demo6.py
# @Software: PyCharm
d={'name':'张三','name':'李四'} #key不允许重复
print(d)
d={'height':185,'weight':185} #value允许重复
print(d)
#字典无序,不能插入
lst=[10,20,40]
lst.insert(1,100)
print(lst)
# d={lst:100} #TypeError: unhashable type: 'list',列表不允许做键,键必须是不可变对象
# print(d)
#字典会浪费较大空间,不按顺序存储,是一种空间换时间的方法,通过哈希函数计算位置查找位置即可,不用管有多少个数据
# -*- coding: utf-8 -*-
# @Time : 2021/9/27 11:19
# @Author : 李新宇
# @FileName: demo7.py
# @Software: PyCharm
#字典生成式
items=['fruits','books','others']
prices=[12,13,14,30,40]
d={ item.upper():price for item,price in zip(items,prices) }#upper()变大写
print(d)