字典的方法
阿新 • • 發佈:2018-08-15
改變 del 類型 互換 one spa int 方法 pda
#字典的KEY只能是不可變數據類型:(int bool 字符串 元祖) (可變數據類型:list dict set) # dic = {1: 1, ‘age‘: 18, ‘name‘: ‘huang‘, (1, 2): ‘abc‘} # print(dic) #增 # dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘,} # dic[‘sex‘] = ‘male‘ #沒有KEY,添加 # dic[‘age‘] = 16 #如果有key,則值覆蓋 # print(dic) # dic.setdefault(‘weight‘) #沒有KEY,添加,默認是None# dic.setdefault(‘weight‘, 50) #已經有KEY就不改變 # print(dic) #刪 # dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘} # print(dic.pop(‘name‘)) #刪除KEY時返回的是value,如果KEY不存在則出錯 # print(dic.pop(‘age‘, None)) #刪除KEY時返回的是value,如果KEY不存在則返回None而不會出錯 # print(dic) # dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘}# del dic # print(dic) # dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘} # print(dic.clear()) #清空 #改 # dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘} # dic[‘age‘] = 33 #直接改已存在的KEY值 # print(dic) # dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘} # dic2 = {‘name‘: ‘haisheng‘, ‘sex‘: ‘male‘, ‘birth‘: 1992}# dic.update(dic2) #如果KEY相同則更新value,否則更新所有新的鍵值對 # print(dic) #查 # dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘} # print(dic.keys()) #打印KEY,返回列表[‘name‘, ‘age‘, ‘work‘] # print(dic.values()) #打印字典的值[‘huang‘, 26, ‘IT‘] # print(dic.items()) #打印字典的項[(‘name‘, ‘huang‘), (‘age‘, 26), (‘work‘, ‘IT‘)] # for k in dic: # 相當於 for k in dic.keys(): # print(k) # # for v in dic.values(): #返回value # print(v) # # for i in dic.items(): #返回的是元祖 (‘name‘, ‘huang‘) # print(i) # for k, v in dic.items(): #返回的是鍵值對應關系 # print(k, v) # v = dic[‘age‘] #查字典的KEY對應的值,如果沒有KEY則報錯 # print(v) # # v = dic.get(‘age1‘, None) #查字典的KEY對應的值,如果沒有KEY則不報錯,返回None # print(v)
#a, b = 1, 2
#a, b =b, a a和b互換
字典的方法