python 基础知识4 - 字典
1、字典增
#字典增 dic = {'name': '大白', 'age': 20} dic['hight'] = 180 #没有键值对,添加 dic['age'] = 18 #有键值对,覆盖 print(dic) #{'name': '大白', 'age': 20, 'hight': 180} #{'name': '大白', 'age': 18 #setdefault dic = {'name': '大白', 'age': 20} dic.setdefault('weight',150)# 没有height此键,则添加 print(dic)#{'name': '大白', 'age': 20, 'weight': 150} dic.setdefault('name',150)# 有此键则不变 print(dic)#{'name': '大白', 'age': 20}
2、字典删
dic = {'name': '大白', 'age': 20} print(dic.pop('age'))#20(有返回值) print(dic.pop('hight','没有此键'))#没有此键 print(dic)#{'name': '大白'} #popitem 3.5版本之前,popitem为随机删除,3.6之后为删除最后一个,有返回值 dic = {'name': '大白', 'age': 20} dic.popitem() print(dic)#{'name': '大白'} #clear 清空字典 dic = {'name': '大白', 'age': 20} dic.clear() print(dic) # {} # del # 通过键删除键值对 dic = {'name': '大白', 'age': 20} del dic['name'] print(dic) # {'age': 20} #删除整个字典 del dic
3、字典改
#update dic1 = {'name':'jin','age':18,'sex':'mal'} dic2 = {'name':'alex','weight':75} dic1.update(dic2)#将2更新到1里 print(dic1) # {'name': 'alex', 'age': 18, 'sex': 'male', 'weight': 75} print(dic2) # {'name': 'alex', 'weight': 75}
4、字典查
#keys()查键 dic = {'name': '大白', 'age': 20} print(dic.keys()) # dict_keys(['name', 'age']) #values()查键值 dic = {'name': '大白', 'age': 20} print(dic.values()) #dict_values(['大白', 20]) #items()查键值对 dic = {'name': '大白', 'age': 20} print(dic.items()) #dict_items([('name', '大白'), ('age', 20)]) for i in dic.items(): print(i) # ('name', '大白') # ('age', 20)
for i,j in dic.items():
print(i,j)
# name 大白
# age 20
#get dic = {'name': '大白', 'age': 20} print(dic.get('age'))#20 print(dic.get('hight'))#(若无)None
4、dict嵌套
dic = {'name':['大白','python','小白'], 'py9': {'num': 71, 'age': 18}, True: 1, (1, 2, 3): '123', 2: '白鸽', } dic['name'][1]=dic['name'][1].upper()#将'name'中‘python'大写 dic['py9']['female'] = 6#将'female':6添加到'py9'中 print(dic)