文章目录
字典
字典的定义
scores={'张三':100,'李四':98,'王五':45} #三个键值对
# scores--->字典名 '张三'--->键 冒号 100--->值
字典的原理
注意:key一定是不可变序列(不可以执行增删改操作)——字符串str、整数序列range。
可变序列(可以执行增删改操作)——字典、列表
字典的创建
#使用{}创建字典
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) # {}
字典元素的常用操作
字典中元素的获取
scores={'张三':100,'李四':98,'王五':45}
# 第一种方式:使用[]
print(scores['张三']) # 100
#print(scores['陈六']) #报错 KeyError: '陈六'
# 第二种方式:使用get()
print(scores.get('张三')) # 100
print(scores.get('陈六')) # None
print(scores.get('麻七',99)) # 99 99是在查找'麻七'所对应的value不存在时,提供的一个默认值
key的判断
scores={'张三':100,'李四':98,'王五':45}
print('张三' in scores) #True
print('张三' not in scores) #False
字典元素的删除
scores={'张三':100,'李四':98,'王五':45}
del scores['张三']
print(scores) # {'李四': 98, '王五': 45}
scores.clear() #清空字典的元素
print(scores) #{}
字典元素的新增
scores={'张三':100,'李四':98,'王五':45}
scores['陈六']=88
print(scores) #{'李四': 98, '王五': 45, '陈六': 88}
#进行修改
scores['陈六']=100
print(scores) #{'李四': 98, '王五': 45, '陈六': 100}
获取字典视图的三个方法
scores={'张三':100,'李四':98,'王五':45}
# 获取所有的key
keys=scores.keys()
print(keys) # dict_keys(['张三', '李四', '王五'])
print(type(keys)) # <class 'dict_keys'>
print(list(keys)) # 将所有key组成的视图转成列表 ['张三', '李四', '王五']
# 获取所有value
values=scores.values()
print(values) # dict_values([100, 98, 45])
print(type(values)) # <class 'dict_values'>
print(list(values)) # [100, 98, 45]
#获取所有key-value对
items=scores.items()
print(items) # dict_items([('张三', 100), ('李四', 98), ('王五', 45)])
print(type(items)) # <class 'dict_items'>
print(list(items)) # 转换之后的列表元素是由元组()组成的 [('张三', 100), ('李四', 98), ('王五', 45)]
字典元素的遍历
scores={'张三':100,'李四':98,'王五':45}
for item in scores:
print(item,scores[item],scores.get(item))
输出:
张三 100 100
李四 98 98
王五 45 45
字典的特点
# key 不允许重复
d={'name':'张三' , 'name':'李四'}
print(d) #{'name': '李四'}
# value可以重复
d={'name':'张三','nikename':'张三'}
print(d) #{'name': '张三', 'nikename': '张三'}
#如果字典的key是可变对象list,则会报错
lst=[10,100,60]
d={lst:100}
print(d) # TypeError: unhashable type: 'list'
字典生成式
items=['Fruits','Books','Others']
prices=['96','78','85']
d={item.upper():price for item, price in zip(items,prices)}
print(d) #{'FRUITS': '96', 'BOOKS': '78', 'OTHERS': '85'}
#upper()---将items中所有字母变大写