1 info = { 2 ‘stu1101‘: "TengLan Wu", 3 ‘stu1102‘: "LongZe Luola", 4 ‘stu1103‘: "XiaoZe Maliya", 5 }
二、增加
1 >>> info["stu1104"] = "苍井空" 2 >>> info 3 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1104‘: ‘苍井空‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘TengLan Wu‘}
三、修改
1 >>> info[‘stu1101‘] = "武藤兰" 2 >>> info 3 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘武藤兰‘}
四、删除
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‘}
五、查找
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‘
六、多级字典嵌套及操作(略)
七、循环字典
1 #方法1 2 for key in info: 3 print(key,info[key]) 4 #方法2 5 for k,v in info.items(): # 会先把dict转成list,数据里大时莫用 6 print(k,v)
1 #values 2 >>> info.values() 3 dict_values([‘LongZe Luola‘, ‘XiaoZe Maliya‘]) 4 #keys ##相对常用 5 >>> info.keys() 6 dict_keys([‘stu1102‘, ‘stu1103‘]) 7 #setdefault 8 >>> info.setdefault("stu1106","Alex") 9 ‘Alex‘ 10 >>> info 11 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} 12 >>> info.setdefault("stu1102","龙泽萝拉") 13 ‘LongZe Luola‘ 14 >>> info 15 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} 16 #update 17 >>> info 18 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} 19 >>> b = {1:2,3:4, "stu1102":"龙泽萝拉"} 20 >>> info.update(b) 21 >>> info 22 {‘stu1102‘: ‘龙泽萝拉‘, 1: 2, 3: 4, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} 23 #items 24 info.items() 25 dict_items([(‘stu1102‘, ‘龙泽萝拉‘), (1, 2), (3, 4), (‘stu1103‘, ‘XiaoZe Maliya‘), (‘stu1106‘, ‘Alex‘)]) 26 #通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个 27 >>> dict.fromkeys([1,2,3],‘testd‘) 28 {1: ‘testd‘, 2: ‘testd‘, 3: ‘testd‘}
原文:http://www.cnblogs.com/chhphjcpy/p/6063708.html