Python dict 字典

 

 

 

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 
 5 test_dict = {
 6     "apple": "iphone 11",
 7     "huawei": "huawei mate30 pro",
 8     "xiaomi": "xiaomi 9 pro",
 9     "alibaba": "alipay"
10 
11 }
12 
13 print(test_dict)
14 print(test_dict.keys())
15 print(test_dict.values())
16 print(test_dict.items())
17 
18 
19 #循環
20 #第一種效率更高,第2種須要先轉換字典
21 for i in test_dict:
22     print(i, test_dict[i])
23 
24 for i, x in test_dict.items():
25     print(i, x)
26 
27 #————————————————————————————————————————————————————
28 
29 test_dict.setdefault("tx", "qq")                #setdefault 若是不存在 "tx" 這個字典則插入值爲 賦予的,存在這查詢出來
30 print(test_dict)
31 test_dict.setdefault("alibaba", "qq")
32 print(test_dict)
33 
34 #----------------------------------------------------
35 b = {
36     "alibaba": "taobao",
37     2: 3,
38     1: 5
39 }
40 
41 test_dict.update(b)                     #update 將已存在的修改,不存在的插入
42 print(test_dict)
43 
44 #----------------------------------------------------
45 
46 c = dict.fromkeys({6, 7, 8}, "test")   #初始化一個字典,
47 print(c)
48 c[6] = "bbbb"                           #修改建議用一層
49 print(c)
50 
51 #----------------------------------------------------
52 
53 
54 
55 
56 #增長
57 test_dict["google"] = "piexl"
58 print(test_dict)
59 
60 #刪除
61 del test_dict["xiaomi"]             #這是python內置的通用刪除方法
62 print(test_dict)
63 test_dict.pop("huawei")             #字典的刪除方法
64 print(test_dict)
65 
66 #修改
67 test_dict["apple"] = "iphone 11 pro"
68 print(test_dict)
69 
70 #查詢
71 print(test_dict["apple"])           #這種查詢若是不存在則會報錯
72 print(test_dict.get("apple1"))      #get 不存在則顯示none
73 print("apple" in test_dict)         #判斷是否存在
相關文章
相關標籤/搜索