字典的相关操作
1. keys() 获取到所有的键
2. values() 获取到所有的值
3. items() 拿到所有的键值对
# dic = {"赵四":"刘晓光", "刘能":"王晓利", "王木生":"范伟"} # 直接for循环 # for key in dic: # 直接循环字典拿到的是key, 有key直接拿value # print(key) # print(dic[key]) # dic = {"赵四":"刘晓光", "刘能":"王晓利", "王木生":"范伟"} # 不常用的 # print(dic.keys()) # dict_keys(['赵四', '刘能', '王木生']) 像列表. 山寨列表 # for k in dic.keys(): # 拿到的是字典中的每一个key # print(k) # 当需要单独获取到所有value的时候 # print(dic.values()) # dict_values(['刘晓光', '王晓利', '范伟']) 所有的value的一个数据集 # for v in dic.values(): # print(v) # print(dic.items()) # 所有的键值对 dict_items([('赵四', '刘晓光'), ('刘能', '王晓利'), ('王木生', '范伟')]) # for k, v in dic.items(): # 遍历字典最简单的方案 # # print(item) # ('赵四', '刘晓光') # # k, v = item # 解构 # # k = item[0] # # v = item[1] # print(k, v) # a, b = 1, 2, 3 # 把后面的两个值分别赋值给前面两个变量. 解构, 解包 # print(a) # print(b) # c = 1,2,3 # print(c) # (1, 2, 3) # 元组和列表是可以解包的 # d, e, f = [1,2,3] # print(d) # print(e) # print(f) # 遍历字典两套方案 dic = {"赵四":"刘晓光", "刘能":"王晓利", "王木生":"范伟"} # 1. 使用for循环直接遍历字典的key # for key in dic: # print(key) # print(dic[key]) # 2. 可以使用字典的items()+解构可以直接获取到key和value # for k, v in dic.items(): # print(k) # print(v)
字典的嵌套
wf = { "name":"汪峰", "age":52, "hobby":["唱歌", "上头条", "穿皮裤"], "wife": { "name": "章子怡", "age": 49, "hobby":["演戏", "上电视", "当导师"], "tishen": { "name":"萌萌", "age":28 }, "zhuli":{ "name":"磊磊", "age": 20 } }, "zhuli":{ "name":"宝宝", "age":23, "hobby":["抽烟","喝酒","烫头"] }, "children":[{"name":"汪老大"}, {"name":"汪老二"}] } # wf['children'][1]["age"] = 2 # print(wf) # # print(wf['zhuli']['name']) # # # 汪峰老婆替身的名字 # print(wf['wife']['tishen']['name']) # # 汪峰老婆的第二个爱好 # print(wf['wife']['hobby'][1]) # # 汪峰助理的第三个爱好 # print(wf['zhuli']['hobby'][2]) # # # # 汪峰的助理+10岁 # wf['zhuli']['age'] = wf['zhuli']['age'] + 10 # # 汪峰的老婆添加一个爱好("导戏") # wf['wife']['hobby'].append("导戏") # 添加完毕了 # # 删除汪峰助理的"抽烟"爱好 # wf["zhuli"]["hobby"].remove("抽烟") # print(wf)