# 字典:Python内置的数据结构之一,与列表一样是一个可变序列(可执行增删改操作);以键值对的方式存储数据,字典是一个无序的序列。
# 字典的创建
# 使用花括号
scores={'张三':100,'李四':98,'王五':45}
print(scores)
print(type(scores))
# 使用内置函数
student=dict(name='jack',age=20)
print(student)
# 创建空字典
d={}
print(d)
# 字典中元素的获取
scores={'张三':100,'李四':98,'王五':45}
print(scores['张三'])
print(scores.get('李四')) #print(scores.get('麻九')) 如果查找的键不存在,会报错
print(scores.get('麻六')) #如果查找的键不存在,会输出NONE
print(scores.get('麻六',99)) #99是在查找其对应value不存在时,提供的一个默认值
#key的判断
print('张三' in scores)
print('张三' not in scores)
#字典元素的删除
scores={'张三':100,'李四':98,'王五':45}
del scores['张三'] #删除一个元素 key为'张三' 或者 DictDelete(key)函数
print(scores)
#清空字典元素
scores.clear()
print(scores)
# 字典的新增
#新增健值对
scores={'lily':30,'abby':90}
scores['lily']=90 #在键为'lily'的Dict中新增值 90
scores['jack']=98 #新增jack值为98
print(scores)
# 获取所有key
scores={'张三':100,'李四':98,'王五':45}
key=scores.keys()
print(key)
print(type(key))
#转成列表
print(list(key)) #将Dict中的键转换为列表
# 获取所有的value
value=scores.values()
print(value)
print(type(value),list(value))
#获取所有的key-value 对
item=scores.items()
print(item)
print(list(item)) #将Dict中的元素转换为列表,转换之后的列表元素由元组组成
# 字典元素的遍历
# 字典元素的遍历时依次获取字典中的元素,item是指字典中的键,也将会输出字典中所有的键。
scores={'张三':100,'李四':98,'王五':45}
for item in scores:
print(item,scores[item],scores.get(item))
# 字典的特点
#字典的元素是无序的
#字典中的key必须是不可变对象
#字典也可以根据需要动态地伸缩
#字典会浪费较大的内存,是一种使用空间换时间的数据结构
#key不能重复,value可以重复
d={'name':'张三','name':'李四'}
print(d) #key重复,value被覆盖掉
#value可以重复
a={'name':'lily','nikename':'lily'}
print(a)
# 字典生成式
# 使用内置函数zip():将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表。
items=['Fruits','Books','others']
prices=[96,78,85]
# lst=zip(items,prices) #如果列表的元素长短不一样,则以短的元素生成
# print(lst)
# print(list(lst))#将对应的元素打包成元组
d={item:price for item,price in zip(items,prices) }
print(d)
a={item.upper():price for item,price in zip(items,prices)} #将字符串转换为大写并将其存储在一个字典中。
print(a)