• Python--字典基本操作


    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author:Huanglinsheng
    
    
    # 字典的特性:
    # dict是无序的
    # key必须是唯一的,so 天生去重
    
    info = {
        'stu1': "TengLan Wu",
        'stu2': "LongZe Luola",
        'stu3': "XiaoZe Maliya",
    }
    print(info.values())
    print(info.keys())
    
    #setdefault
    info.setdefault("stu6","Alex")
    
    #增加
    info["stu4"] = "hls"
    
    #修改
    info["stu4"] = "hc"
    
    #删除
    info.pop("stu4")
    del info["stu3"]
    info.popitem()  #随机删除
    
    #查找
    # "stu1102" in info   #标准用法
    # info.get("stu1102")  #获取
    # info["stu1102"] #同上,但是看下面
    # info["stu1105"]  #如果一个key不存在,就报错,get不会,不存在只返回None
    
    #update
    b = {1:2,3:4, "stu1102":"龙泽萝拉"}
    info.update(b)
    
    #items
    # info.items()
    # dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])
    
    #循环dict
    #方法1
    for key in info:
        print(key,info[key])
    
    #方法2
    for k,v in info.items(): #会先把dict转成list,数据里大时莫用
        print(k,v)
    
    
    
    
    
    
    
    
    
    
    
    
    
    #多级字典嵌套及操作
    youlan = {
        "运维":{
            "hc":["帅气","威猛"],
            "hls":["菜鸡","挖坑王"]
        },
        "运营":{
            "hht":["靓仔","大佬"],
            "lm":["美女","可爱"]
        },
        "服务端":{
            "cyl":["大佬","牛逼"],
            "zcw":["美女","可爱"]
        }
    }
    
    youlan["运维"]["hc"][1] = youlan["运维"]["hc"][1] + "牛逼"
    print(youlan["运维"]["hc"][1])
    for k in youlan:
        print(k)

    =======================经典案例==================================

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author:Huanglinsheng
    
    menu = {
        '北京':{
            '海淀':{
                '五道口':{
                    'soho':{},
                    '网易':{},
                    'google':{}
                        }
                    }
                },
        '山东':{},
    }
    
    
    exit_flag = False
    current_layer = menu
    print(menu)
    
    layers = []
    
    while not  exit_flag:
        for k in current_layer:
            print(k)
        choice = input(">>:").strip()
        if choice == "b":
            current_layer = layers[-1]
            print(current_layer)
            #print("change to laster", current_layer)
            layers.pop()
        elif choice not  in current_layer:continue
        else:
            layers.append(current_layer)
            print(layers)
            current_layer = current_layer[choice]
            print(current_layer)
  • 相关阅读:
    Linq 中的Select事例
    C#关于事件的几个好例子
    C#运用实例.读取csv里面的词条,对每一个词条抓取百度百科相关资料,然后存取到数据库
    cookie 和 session 基本使用 以及 封装
    javascript 兼容各个浏览器的事件
    jquery选择器从认识到使用初级篇
    作业八—Alpha阶段项目总结
    第十四次
    第十三次
    十二次
  • 原文地址:https://www.cnblogs.com/huanglinsheng/p/9361240.html
Copyright © 2020-2023  润新知