1 # 增 2 dic = {"name":"周杰倫","age":45,"sex":"boy","money":100000} 3 dic["sex"] = "女" #增長,若是key重複了,會替換掉原來的value 4 print(dic) 5 dic.setdefault("hobby","listen music") 6 print(dic)
1 # 刪 2 dic = {"name":"周杰倫","age":45,"sex":"boy","money":100000} 3 ret = dic.pop("money") #有返回值,返回的是被刪除的value 4 print(dic) #{'name': '周杰倫', 'age': 45, 'sex': 'boy'} 5 print(ret) #被刪除的值 6 del dic["sex"] #{'name': '周杰倫', 'age': 45, 'money': 100000} 7 print(dic) 8 dic.popitem() #隨機刪除 9 print(dic) #{'name': '周杰倫', 'age': 45, 'sex': 'boy'} 10 dic.clear() #所有清空 {} 11 print(dic)
1 #改 2 dic = {"name":"周杰倫","age":45,"sex":"boy","money":100000} 3 dic["age"] = "40" #強制修改值 4 print(dic) #{'name': '周杰倫', 'age': '40', 'sex': 'boy', 'money': 100000} 5 dic1 = {"name":"李晨","bug":"惟一一個","age":38} 6 dic2 = {"name":"范冰冰","鄧超":"瑪麗","age":26} 7 dic2.update(dic1) #把dic1中的內容更新到dic2中,若是存在了key,則替換,若是不存在,則添加進去 8 print(dic1) 9 print(dic2)
1#查
2 dic = {"name":"周杰倫","age":45,"sex":"boy","money":100000} 3 print(dic.get("sex")) #boy 4 print(dic["age"]) #45 5 for a in dic: #for 循環默認是獲取字典中的鍵(key) 6 print(a) 7 print(dic[a]) #獲取的是字典中的值(value) 8 ret = dic.setdefault("name","謝文東") #首先判斷原來的字典中有沒有這個key,若是沒有,執行新增 9 print(dic) #用這個key去字典中查詢,返回查找到的結果 10 print(ret)
1 dic = {"name":"周杰倫","age":45,"sex":"boy","money":100000} 2 print(dic.keys()) #獲取到全部的鍵存在一個高仿的列表中 3 ##dict_keys(['name', 'age', 'sex', 'money']) 4 print(dic.values()) #獲取到全部的值存在一個高仿的列表中 5 ##dict_values(['周杰倫', 45, 'boy', 100000]) 6 print(dic.items()) #獲取到全部的鍵值對,以元組的形式存在一個高仿的列表中 7 ##dict_items([('name', '周杰倫'), ('age', 45), ('sex', 'boy'), ('money', 100000)])
1 # 字典的嵌套 2 dic1 = { 3 "name":"汪峯", 4 "age":48, 5 "sex":"男", 6 "wife":{ 7 "name":"章子怡", 8 "age":36, 9 "sex":"女", 10 }, 11 "baby":[ 12 {"name":"熊大","age":18}, 13 {"name":"熊二","age":16} 14 ] 15 } 16 print(dic1) 17 dic1["baby"][1]["age"] = 14 18 print(dic1)