1.3 - 字典练习题

 1 # 1.循环遍历所有得key
 2 dic = {'K1': 'v1', 'K2': 'v2', 'K3': 'v3'}
 3 
 4 print(dic)
 5 
 6 for i in dic.keys():
 7     print(i)
 8 
 9 # 2.循环遍历所有得value
10 for j in dic.values():
11     print(j)
12 
13 # 3.循环遍历所有得key和value
14 for k, v in dic.items():   //这种方法不用效率低
15     print(k, v)
16 for k in dic:
17     print(k,dic[k])
18 
19 # 4.添加键值对 并输出
20 dic['K4'] = 'v4'
21 print(dic)
22 
23 # 5.删除了K1键值对
24 dic.pop('K1')
25 del dic['K1']
26 print(dic)
27 
28 # 6.删除K5 不存在返回 None
29 result = dic.get('K5')
30 if result != None:
31     dic.pop('K5')
32 else:
33     print(result)
34 
35 # 7.获取字典中 K2对应得值
36 # result = dic['K2']
37 result = dic.get('K2')
38 print(result) 
39 
40 # 8.获取K6不存在返回None
41 result = dic.get('K6')
42 print(result)
43 
44 # 9.dic2 更新 被dic
45 dic2 = {'K1': 'v111', 'a': 'b'}
46 print(dic,dic2)
47 dic2.update(dic)
48 print(dic,dic2)
49 
50 # 10.列表 字典 嵌套
51 Lis = ['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']
52 print(Lis)
53 
54 # Lis[1][2].get('k1')[0] = 'TT'
55 Lis[1][2].get('k1')[0] = Lis[1][2].get('k1')[0].upper()
56 print(Lis)
57 
58 Lis[1][2].get('k1')[1] = '100'
59 print(Lis)
60 
61 Lis[1][2].get('k1')[-1] = 101
62 print(Lis)
63 
64 # 11.将列表得奇数位 添加到字典中 
65 li = [1, 2, 3, 'a', 'b', 4, 'c']
66 dic = {}
67 dic.setdefault('K1',[])
68 for index, i in enumerate(li):
69     if index % 2 == 1:
70         dic['K1'].append(i)
71 
72 print(dic)
posted @ 2018-02-07 16:52  Alice的小屋  阅读(272)  评论(1编辑  收藏  举报