使用{}创建字典
scores={'张三':100,‘李四’:88,‘王五’:63} #键值对
print(scores)
print(type(scores))
使用内置函数dict()创建字典
student=dict(name='jack',age=20)
print(student)
空字典 d={}
字典元素的获取
scores={'张三':100,‘李四’:95,‘王五’:45}
第一种方式: print(scores['张三'])
第二种方式: print(scores.get('张三'))
获取所有的key
keys=scores.keys()
print(keys)
print(list(keys)) #将所有的key组成的视图转成列表
获取所有的value
values=scores.values()
print(values)
print(list(values))
获取所有的key-value对
items=scores.items()
print(items)
print(list(items)) #转换之后的列表元素是由元素组成
字典的遍历
for item in scores:
print(item,scores[item])
字典的特点:
key不允许重复,value可以重复
字典中的元素是无序的
字典中的key必须是不可变对象
浪费较大的内存,是一种使用空间换时间的数据结构
字典生成式:
items=['Fruits','Books']
prices=[96,78]
d={item.upper():price for item,price in zip(items,price)}