#字典是key-value的数据类型,字典是无序的,没有下标(列表有下标),key必须是唯一的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
info = {
    "stu001":"fengxiaoli",
    "stu002":"cx",
    "stu003":"wyc",
    "stu004":"ljh",
}
 
 
###-----------------循环字典
for in info:              #推荐使用
    print(i,info[i])
 
for k,v in info.items():    #不推荐,因为它是先转化为列表在打印,数据量的时候数据会很慢
    print(k,v)
     
     
###-----------------查询
print("stu001" in info)     #判断key是否在字典中,同py2中 info.has_key("stu001")
print(info.get("stu002"))   #通过key获取value,推荐使用
print(info["stu001"])
print(info)  
     
     
###-----------------修改
info["stu003"= "fzl"        #有那个key就修改,没有新增
info["stu005"= "fzl"
print(info)
 
 
###-----------------删除
del info                       #删除整个字典
del info["stu005"]
info.pop("stu004")
info.popitem()                 #随机删除一组
 
 
###-----------------合并两个字典
= {
    "stu001":"fxl",
    3:5,
    4:8,
}
info.update(b)      #合并字典info和字典b,有重复的就更新,不重复的就合并
print(info)
 
 
###-----------------把字典转成列表
print(info.items())
 
 
###-----------------初始化一个字典
= dict.fromkeys([7,8,9],"test")
print(c)
#输出{8: 'test', 9: 'test', 7: 'test'}
 
c1 = dict.fromkeys([7,8,9],{1:"feng",2:"cx",3:"fxl"})
print(c1)
#输出{8: {1: 'feng', 2: 'cx', 3: 'fxl'}, 9: {1: 'feng', 2: 'cx', 3: 'fxl'}, 7: {1: 'feng', 2: 'cx', 3: 'fxl'}}
 
c1[8][2]="xia"      #类似浅copy,二级字典中数据指向同一内存地址,修改一个所有都改变
print(c1)
#输出{8: {1: 'feng', 2: 'xia', 3: 'fxl'}, 9: {1: 'feng', 2: 'xia', 3: 'fxl'}, 7: {1: 'feng', 2: 'xia', 3: 'fxl'}}
    
    
 
###-----------------多级字典
info2 = {
    "stu001":{"fxl":["性别:男","年龄:21"]},
    "stu002":{"cx":["性别:女","年龄:25"]},
    "stu003":{"fzl":["性别:男","年龄:35"]},
}
info2["stu001"]["fxl"][1= "年龄:23"            #修改
info2.setdefault("stu004",{"ljh":["性别:女","年龄:40"]})     #增加,如果字典中有这个key就不改变原值,没有就新建
print(info2)