[Python Study Notes]字典操作

                     

 字典操作    

                                                                   

 

a.增加

1 >>> info["stu1104"] = "abc"
2 >>> info
3 {'stu1102': 'x5456', 'stu1104': 'abc', 'stu1103': 'Mali', 'stu1101': 'Wu'}

 b.修改

1 >>> info['stu1101'] = "xinge"
2 >>> info
3 {'stu1102': 'x5456', 'stu1103':  Mali', 'stu1101': 'xinge'}

 c.删除

 1 >>> info
 2 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
 3 >>> info.pop("stu1101") #标准删除姿势
 4 '武藤兰'
 5 >>> info
 6 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
 7 >>> del info['stu1103'] #换个姿势删除
 8 >>> info
 9 {'stu1102': 'LongZe Luola'}
10 >>> 
11 >>> 
12 >>> 
13 >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
14 >>> info
15 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除
16 >>> info.popitem()
17 ('stu1102', 'LongZe Luola')
18 >>> info
19 {'stu1103': 'XiaoZe Maliya'}

 d.查找

 1 >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
 2 >>> 
 3 >>> "stu1102" in info #标准用法
 4 True
 5 >>> info.get("stu1102")  #获取
 6 'LongZe Luola'
 7 >>> info["stu1102"] #同上,但是看下面
 8 'LongZe Luola'
 9 >>> info["stu1105"]  #如果一个key不存在,就报错,get不会,不存在只返回None
10 Traceback (most recent call last):
11   File "<stdin>", line 1, in <module>
12 KeyError: 'stu1105'

 e.获取键值

1 #values
2 >>> info.values()
3 dict_values(['LongZe Luola', 'XiaoZe Maliya'])
4 
5 #keys
6 >>> info.keys()
7 dict_keys(['stu1102', 'stu1103'])

 

f.合并

1 #update 
2 >>> info
3 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
4 >>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}
5 >>> info.update(b)
6 >>> info
7 {'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}

 

g.深copy

1 import copy
2    
3 n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
4    
5 n4 = copy.deepcopy(n1)

 

h.循环

1 #方法1
2 for key in info:
3     print(key,info[key])
4  
5 #方法2
6 for k,v in info.items(): #会先把dict转成list,数据里大时莫用
7     print(k,v)

 

posted @ 2018-01-09 14:51  刘六六  阅读(204)  评论(0编辑  收藏  举报