zoukankan      html  css  js  c++  java
  • 字典的相关操作

    字典的相关操作

    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)
    

      

  • 相关阅读:
    IOS之推送通知(本地推送和远程推送)
    IOS,苹果内购和添加广告
    CSS3选择器、背景、边框、文本
    CSS2D旋转、过渡、动画
    JavaScript Array、Date、String
    那些不常用却很有的CSS
    纯CSS打造兼容各种浏览器的几何图形
    安装 SQLManagementStudio_x86_CHS(SQL Server Management Studio) 老提示重启的解决办法
    关于使用Html.RenderPartial和Html.Partial显示分部视图时提示参数错误的BUG
    学习从实践开始之jQuery插件开发:对话框插件开发
  • 原文地址:https://www.cnblogs.com/YangWenYu-6/p/10060759.html
Copyright © 2011-2022 走看看