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)         #判断是否存在

 

posted on 2019-10-11 14:30  voua  阅读(90)  评论(0编辑  收藏  举报

导航