今天学习了数据容器——字典(dict),顺便把学习的内容自我消化一遍,在这里整理记录一下,方便日后的使用查阅
字典的主要特点:
dict1={'yazhang':99,'xiaoyou':98,'qingqing':70} #定义一个非空字典
dict2={} #定义一个空字典
dict3=dict() #通过字典对象定义一个空字典
dic4={"张三":{
"部门":"市场部",
"工资":5000,
"级别":1
},
"李四":{
"部门":"企划部",
"工资":8000,
"级别":2
},
"王五": {
"部门": "科技",
"工资": 9000,
"级别": 3
},
} #字典里面嵌套字典
通过字典名称[key]获得对应的value值
dict2={'yazhang':99,'xiaoyou':98,'qingqing':70}
print(dict2['yazhang']) #结果:通过key=yazhang,获得对应的value值=99
通过字典名称[新key]增加字典元素
dict2={'yazhang':99,'xiaoyou':98,'qingqing':70}
dict2['xiaowang']=65 #原字典中不存在xiaowang这个key值,那就是新增元素
print(dict2) #结果:{'yazhang':99,'xiaoyou':98,'qingqing':70,'xiaowang':65}
通过字典名称[已有key]=新value,修改原有的value值
dict3={'yazhang':99,'xiaoyou':98,'qingqing':70}
dict3['yazhang']=88 #原字典修改yazhang这个key对应的value值,99→88
print(dict3) #结果:{'yazhang':88,'xiaoyou':98,'qingqing':70}
通过字典名称.pop('yazhang')
dict4={'yazhang':99,'xiaoyou':98,'qingqing':70}
value=dict4.pop('yazhang') # 移除yazhang对应的元素
print(value,dict4) #结果:value=99, dict4={'xiaoyou':98,'qingqing':70}
通过字典名称.clear()
dict5={'yazhang':99,'xiaoyou':98,'qingqing':70}
dict5.clear() # 清空字典
print(dict5) #结果:dict5={}
通过字典名称.keys()
dict6={'yazhang':99,'xiaoyou':98,'qingqing':70}
keys=dict6.keys() # 获取字典的key值
print(keys) #结果:keys=dict_keys(['yazhang', 'xiaoyou', 'qingqing'])
方法一:
通过字典名称.keys()获取字典的所有key值,再通过字典名称.[key]获得对应的value值
dict6={'yazhang':99,'xiaoyou':98,'qingqing':70}
keys=dict6.keys() # 获取字典的key值
print(keys) #结果:keys=dict_keys(['yazhang', 'xiaoyou', 'qingqing'])
for key in keys:
print('key=',key,'value=',dict6[key])
方法二:(推荐)
dict7={'yazhang':99,'xiaoyou':98,'qingqing':70}
for key in dict7:
print('key=',key,'value=',dict7[key])
通过len(字典名称)获取字典的数据个数
dict6={'yazhang':99,'xiaoyou':98,'qingqing':70}
num=len(dict6) # 获取字典的数据个数
print(num) #结果:num=3