字典
- 1. 字典的概述
- 2. 字典增删改查
- 3. 字典其他操作
- 4. 字典的嵌套
1. 字典的概述
- 以{}表示. 每一项用逗号隔开, 内部元素用key:value的形式来保存数据 "jj":"林俊杰", "jay":"周杰伦"
- 查询的效率非常高, 通过key来查找元素,内部使用key来计算一个内存地址(暂时),hash算法
- (key 必须是可哈希的数据类型)可哈希就是不可变
2.字典增删改查
- 字典的新增
dic={} dic["周星驰"] = "少林足球" # 直接用key往里边存数据即可 dic["梁朝伟"] = "无间道" dic["吴孟达"] = "大话西游" dic["吴孟达"] = "食神" # 如果key已经存在,那么会替换掉原来的value,修改 print(dic)
# 如果dict中没有出现过这个key-value. 可以通过setdefault设置默认值 dic={} dic.setdefault("刘德华") dic.setdefault("刘德华","赌侠") # 如果dict中已经存在了了. 那么setdefault将不不会 起作⽤用 print(dic)
注: dic .setdefault()的基本意思是新增,print(dic .setdefault())的结果是它此时key所对应的value值.
- 字典的删除
dic = {"胡军":"天龙八部","李亚鹏":"射雕英雄传","苏有朋":"倚天屠龙记","周星驰":"大话西游"} dic.pop("苏有朋") dic.popitem() # 随机删除 del dic["苏有朋"] #删除 dic.clear() # 清空字典 print (dic)
- 字典的修改
dic = {"刘能":"王小利","赵四":"刘晓光","王木生":"范伟","谢大脚":"于月仙"} # dic["王木生"] = "刘伟" dic2 = {"刘能":"大阳哥","赵四":"github","王木生":"汪峰","谢大脚":"冯提莫","王大拿":"金老板"} dic.update(dic2) #会将dic中存在key,进行替换,不存在,会新增 print(dic)
- 字典的查询
dic = {"刘能":"大阳哥","赵四":"github","王木生":"汪峰","谢大脚":"冯提莫","王大拿":"金老板"} #最直观的用key print(dic["谢大脚"]) print(dic["周杰伦"]) #当在dic中不存在key时,会报错
get方法
dic = {"刘能":"大阳哥","赵四":"github","王木生":"汪峰","谢大脚":"冯提莫","王大拿":"金老板"} print(dic.get("谢大脚")) print(dic.get("周杰伦")) #返回None print(dic.get("周杰伦","周杰伦不在这里"))
# setdefault() 1. 新增(先看有没有key, 如果有就过, 如果没有,执行新增) 2.根据key把值返回 dic = {} dic["盖伦"] = "德玛西亚之力" value = dic.setdefault("菲奥娜", "无双剑姬") # 新增 value2 = dic.setdefault("盖伦", "刘伟") # 由于已经存在了key。 所以新增不执行。 直接查询结果 value3 = dic.setdefault("薇恩", "坑") print(value3) #坑 print(dic) #{'菲奥娜': '无双剑姬', '薇恩': '坑', '盖伦': '德玛西亚之力'}
- fromkey() -- 可以帮我们通过list来创建⼀个dict
dic= {} # fromkeys正常来说应该是类名来访问的. dic1 = dic.fromkeys(["胡辣汤","are you 确定?"], "周芷若") # fromkeys是一个类方法.作用是创建新字典 print(dic) # 原字典没有改变 print(dic1) # 新的字典是通过第一个参数的迭代. 和第二个参数组合成key:value创建新字典 #{} #{'胡辣汤': '周芷若', 'are you 确定?': '周芷若'
dic = dict.fromkeys(["哇哈哈", "爽歪歪"], []) # 所有的key用的都是同一个列表,改变其中一个。 另一个也跟着改变 dic["哇哈哈"].append("张无忌") print(dic) #{'哇哈哈': ['张无忌'], '爽歪歪': ['张无忌']} print(id(dic['哇哈哈']), id(dic["爽歪歪"])) #2512709362824 2512709362824
3.字典的其他操作
- 遍历
# 对字典的遍历 dic = {"汪峰": "大陆音乐半壁江山", "周杰伦": "亚洲音乐天王", "罗志祥": "亚洲舞王"} print(dic.keys()) # dict_keys(['汪峰', '周杰伦', '罗志祥']) 像列表但不是列表 for key in dic.keys(): print(key) # 拿到key print(dic[key]) # 拿到value
dic = {"汪峰": "大陆音乐半壁江山", "周杰伦": "亚洲音乐天王", "罗志祥": "亚洲舞王"} print(dic.values()) for value in dic.values(): print(value)
dic = {"汪峰": "大陆音乐半壁江山", "周杰伦": "亚洲音乐天王", "罗志祥": "亚洲舞王"} # 也可以遍历字典 print(dic.items()) # 拿到的是key和value,# [('汪峰', '大陆音乐半壁江山'), ('周杰伦', '亚洲音乐天王'), ('罗志祥', '亚洲舞王')] for k, v in dic.items(): # 当需要遍历字典. 在操作中涉及到key和value的时候. print(k) # 元组 print(v)
- 另外:
# 字典本身是一个可迭代对象,可以直接进行for循环 dic = {"汪峰": "大陆音乐半壁江山", "周杰伦": "亚洲音乐天王", "罗志祥": "亚洲舞王"} for el in dic: # 直接拿到key print(el) print(dic[el]) #将el换成key
- 字典的迭代中修改
dic = {"谢逊": '金毛狮王', "韦一笑":"青翼蝠王","殷天正":"白眉鹰王","金花婆婆":"紫衫龙王"} for k in dic: dic['谢逊'] = "张无忌义父" print(dic) #{'谢逊': '张无忌义父', '韦一笑': '青翼蝠王', '殷天正': '白眉鹰王', '金花婆婆': '紫衫龙王'} ##字典在迭代中是可以修改的
-
在迭代中删除元素
dic = {"谢逊": '金毛狮王', "韦一笑":"青翼蝠王","殷天正":"白眉鹰王","金花婆婆":"紫衫龙王"} for k in dic: dic.pop(k) print(dic) #报错RuntimeError: dictionary changed size during iteration # 字典在迭代中是不可删除的
- 解决方法
dic = {"谢逊": '金毛狮王', "韦一笑":"青翼蝠王","殷天正":"白眉鹰王","金花婆婆":"紫衫龙王"} lis=[] for k in dic: lis.append(k) for el in lis: dic.pop(el) print(dic)
将要删除的元素暂时先保存在⼀个list中, 然后循环list, 再删除
注:关于解包:
# 前面的变量的个数和后面解包的个数一致 a, b = (10, 20) # 解构, 解包 print(a) print(b)
4. 字典的嵌套
wf = { "name": "汪峰", "age": 48, "成名曲": "春天里", "wife": { "name": "章子怡", "age": 39, "工作": "演员" }, "children":[ {"num": "001", "name": "汪一", "hobby": "唱歌"}, {"num": "002", "name": "汪二", "hobby": "演戏"} # wf['children'][1]['name'] ] } wf['wife']['age'] = wf['wife']['age'] + 10 print(wf)