字典的增刪改查和嵌套
阿新 • • 發佈:2018-01-25
body pre 嵌套 一行代碼 .get dbo clear 增刪改查 value
字典:python中非常重要的數據類型,在python中唯一一個映射的數據類型
數據類型分類
按照數據可變與不可變:
# 不可變數據類型: int str bool tuple
# 可變數據類型: list,dict,set
1 鍵值對
#字典的 key:value# key 是唯一的 且是不可變數據類型 int,str bool tuple
#value:任意數據類型
2 . 增加數據
dic = {"name":"jin","age":18,"sex":"male"} #增 dic[‘key‘] = value # 有key 就覆蓋,沒有key就添加. # dic[‘name2‘] = ‘依米‘ #沒有key name2 就會添加新數據# print(dic) # dic[‘name‘] = ‘王子‘ #有key name 那麽name的值就會被替代 # print(dic)
結果:
.setdefault 方法有key不變, 沒有key才添加.
dic = {"name":"jin","age":18,"sex":"male"}
#有key不變,沒有key才添加.
# dic.setdefault(‘hobby‘) #沒有會添加
# print(dic)
# dic.setdefault(‘hobby‘,‘開船‘)#有就不會變
# print(dic) # dic.setdefault(‘name‘,‘太白‘)#有就不會變# print(dic)
結果:
3. 刪
.pop 按key刪除,有返回值,並且如果沒有此key,可設置返回值.
dic = {"name":"jin","age":18,"sex":"male"} ret = dic.pop(‘sex‘) print(ret) ret = dic.pop(‘sex1‘,‘沒有此鍵‘) print(ret)
結果:
清空和刪除 clear是清空數據 字典還存在 del是刪除字典
dic = {"name":"jin","age":18,"sex":"male"} dic.clear() print(dic) # del 刪除字典,刪除鍵值對del dic print(dic)
結果:
.popitem()隨機刪除一個數據,並產生返回值. 但是python3.6版本以後默認刪除最後一個數據
dic = {"name":"jin","age":18,"sex":"male"} #popitem() 隨機刪除 ret = dic.popitem() print(ret) print(dic)
結果:
4. 改
dic = {"name":"jin","age":18,"sex":"male"} # 改 #dic[‘key‘] = value # 有key 就覆蓋. dic["name"]=(1)
結果:
update 將dic的鍵值對,覆蓋,添加到dic2 中,dic不變
update 將dic的鍵值對,覆蓋,添加到dic2 中,dic不變 dic = {"name":"jin","age":18,"sex":"male"} dic2 = {"name":"alex","weight":75} dic2.update(dic) print(dic) print(dic2)
結果:
5 查
.get方法通過key找值,如果沒有可以加值告知 不添加默認為none
dic = {"name":"jin","age":18,"sex":"male"} # 查 print(dic[‘name‘]) #輸入key 找對應value print(dic.get(‘name‘)) print(dic.get(‘name2‘,‘沒有此鍵值對‘)) print(dic)
結果:
a,b能同時賦值,只要後面有兩個元素, int list dict tuple等類型都行
a = 1 #一行代碼實現a,b值互換
b = 3 a,b = b,a print(a,b) a,b = [‘alex‘,‘wusir‘] print(a,b) a,b = (‘alex‘,‘wusir‘) print(a,b)
結果:
6 找出所有key
dic = {"name":"jin","age":18,"sex":"male"} for k in dic: print(k) for k in dic.keys(): print(k)
7 找出所有values
dic = {"name":"jin","age":18,"sex":"male"} for v in dic.values(): print(v)
結果:
8 找出所有鍵值對;
dic = {"name":"jin","age":18,"sex":"male"} for k,v in dic.items(): print(k,v) for k in dic: print(k,dic[k])
結果:
9 字典的嵌套
dic = {
‘name‘:‘金鑫‘,
‘name_list‘:[1,2,3,‘李傑‘],
1:{
‘python10‘:[‘小黑‘,‘萌哥‘],
‘老男孩‘:{‘name‘:‘oldboy‘,‘age‘:56}
}
}
#1,[1,2,3,‘李傑‘]追加‘wusir‘
#2, [‘小黑‘,‘萌哥‘] 小黑 萌哥中間 插入一個花哥
#3, {‘name‘:‘oldboy‘,‘age‘:56} 添加一個鍵值對,hobby:男人
dic[‘name_list‘].append(‘wusir‘) print(dic) l = dic[1][‘python10‘] l.insert(1,‘花哥‘) print(dic) dic1 = dic[1] dic2 = dic1[‘老男孩‘] dic2[‘hobby‘] = ‘男人‘
結果:
字典的增刪改查和嵌套