1 #Author:ersa 2 ''' 3 key-value 键值对 4 字典是无序的,不需要下标,有key 5 字典的查找、修改、添加、判断、删除 6 ''' 7 8 info = { 9 'stu1101': "TengLan Wu", 10 'stu1102': "LongZe Luola", 11 'stu1103': "XiaoZe Maliya", 12 } 13 14 #输出 15 print("输出所有的key".center(50,'=')) 16 print(info.keys()) 17 print("=".center(70,'=')) 18 19 print("输出所有的 值".center(50,'=')) 20 print(info.values()) 21 print("=".center(70,'=')) 22 23 #循环输出键-值 24 print("输出键-值".center(50,'=')) 25 for i in info: 26 print(i,info[i]) 27 print("=".center(70,'=')) 28 29 #设置默认值:如果有key-value 则返回,没有则创建 30 print("取key-value值,没有则创建".center(50,'=')) 31 info.setdefault("stu1106","Alex") 32 print(info) 33 print("=".center(70,'=')) 34 35 #查找 36 print(info) 37 print("查找".center(50,'=')) 38 print(info["stu1101"]) 39 40 #安全查找--->查找的值不存在时不会报错 41 print("安全查找".center(50,'=')) 42 print(info.get('stu1104')) 43 44 #判断 45 print("判断key是否存在".center(50,'=')) 46 print('stu1104' in info) 47 48 #修改 49 print("修改".center(50,'=')) 50 print(info) 51 52 info["stu1101"] = "武藤兰" 53 #添加 54 print("添加".center(50,'=')) 55 info["stu1104"] = "苍老师" 56 print(info["stu1104"]) 57 58 #删除 Python--->通用删除del 59 print("删除".center(50,'=')) 60 #del info["stu1101"] 61 print(info) 62 63 #字典删除 64 print("字典删除".center(50,'=')) 65 #info.pop("stu1101") 66 print(info) 67 68 #随机删除 69 print("随机删除".center(50,'=')) 70 #info.popitem() 71 print(info) 72 73 #字典转列表 74 print("字典转列表".center(50,'=')) 75 print(info.items()) 76 print("=".center(70,'=')) 77 78 #update 更新字典 79 b = { 80 'stu1101':"alex", 81 1:3, 82 2:5 83 } 84 info.update(b) 85 print("合并字典,有重合key,则更新".center(50,'=')) 86 print(info) 87 print("=".center(70,'=')) 88 89 #初始化新的字典 90 print("初始化新的字典".center(50,'=')) 91 c = dict.fromkeys([6,7,8],'test') 92 print(c) 93 print("=".center(70,'='))