美文网首页
6、字典

6、字典

作者: Yerban | 来源:发表于2018-10-16 18:13 被阅读0次

    字典

    字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

    1. 语法:
    info = {
        'stu1101': "TengLan",
        'stu1102': "LongZe",
        'stu1103': "XiaoZe",
    }
    
    1. 字典的特性:
    • dict是无序的
    • key必须是唯一的,so 天生去重
    1. 增加
    info["stu1104"] = "苍井"
    print(info)
    # {'stu1101': 'TengLan', 'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1104': '苍井'}
    
    
    1. 修改
    info['stu1101'] = "武藤兰"
    print(info)
    # {'stu1101': '武藤兰', 'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1104': '苍井'}
    
    
    1. 删除
    info.pop("stu1101") #标准删除姿势,删除“武藤兰”
    print(info)
    # {'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1104': '苍井'}
    
    del info['stu1103'] #换个姿势删除,删除'XiaoZe'
    print(info)
    # {'stu1102': 'LongZe', 'stu1104': '苍井'}
    
    info = {
        'stu1101': "TengLan",
        'stu1102': "LongZe",
        'stu1103': "XiaoZe",
    }
    
    info.popitem()  #随机删除
    print(info)
    # {'stu1101': 'TengLan', 'stu1102': 'LongZe'}
    
    
    1. 查找
    info = {
        'stu1101': "TengLan",
        'stu1102': "LongZe",
        'stu1103': "XiaoZe",
    }
    
    print("stu1102" in info)  #标准用法
    # True
    print(info.get("stu1102"))  #获取
    # LongZe
    print(info["stu1102"])  #同上,但是看下面
    # LongZe
    print(info["stu1105"])  #如果一个key不存在,就报错,get不会,不存在只返回None
    '''
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'stu1105'
    '''
    
    
    1. 多级字典嵌套及操作
    av_catalog = {
        "欧美":{
            "www.youtuber.com": ["免费的,世界最大的","质量一般"],
            "www.facebook.com": ["免费的,也很大","质量高点"],
            "www.twitter.com": ["图片很多","资源不多"]
        },
        "日韩":{
            "www.tokyometro.jp":["日韩范了","收费的"]
        },
        "大陆":{
            "www.baidu.com":["全部免费,真好,呵呵","好人一生平安"]
        }
    }
    
    # “+=”追加
    av_catalog["大陆"]["www.baidu.com"][1] += ",呵呵"
    print(av_catalog["大陆"]["www.baidu.com"])
    # ["全部免费,真好,呵呵","好人一生平安,呵呵"]
    
    # “=”覆盖
    av_catalog["大陆"]["www.baidu.com"][1] = "呵呵"
    print(av_catalog["大陆"]["www.baidu.com"])
    # ["全部免费,真好,呵呵","好人一生平安,呵呵"]
    
    
    1. 其他函数
    #values 列出字典里所有的value
    >>> info.values()
    dict_values(['LongZe', 'XiaoZe'])
    
    #keys  列出字典里所有的key
    >>> info.keys()
    dict_keys(['stu1102', 'stu1103'])
    
    
    #setdefault 如果原来字典里没有,进行增加
    >>> info.setdefault("stu1106","Alex")
    'Alex'
    >>> info
    {'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}
    # 如果原来字典里有,无法添加,返回原来的值
    >>> info.setdefault("stu1102","龙泽")
    'LongZe'
    >>> info
    {'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}
    
    
    #update 有两个字典,将b合并到info,原本没有的会添加,已经有的会覆盖修改。
    >>> info
    {'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}
    >>> b = {1:2,3:4, "stu1102":"龙泽"}
    >>> info.update(b)
    >>> info
    {'stu1102': '龙泽', 1: 2, 3: 4, 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}
    
    #items
    >>> info.items() #把字典转化为list
    dict_items([('stu1102', '龙泽'), (1, 2), (3, 4), ('stu1103', 'XiaoZe'), ('stu1106', 'Alex')])
    
    
    #通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个
    >>> dict.fromkeys([1,2,3],'testd')
    {1: 'testd', 2: 'testd', 3: 'testd'}
    
    c = dict.fromkeys([1, 2, 3], ['testd', {'name': 'yerban'}, 'books'])
    print(c)
    # {1: ['testd', {'name': 'yerban'}, 'books'], 2: ['testd', {'name': 'yerban'}, 'books'], 3: ['testd', {'name': 'yerban'}, 'books']}
    # 修改一个,会全部修改
    c[2][1]["name"] = "hl"
    print(c)
    # {1: ['testd', {'name': 'hl'}, 'books'], 2: ['testd', {'name': 'hl'}, 'books'], 3: ['testd', {'name': 'hl'}, 'books']}
    
    1. 循环dict
    #方法1,比较高效
    for key in info:
        print(key,info[key])
    
    #方法2,数据大时不建议使用
    for k,v in info.items(): #会先把dict转成list,数据里大时莫用
        print(k,v)
    

    相关文章

      网友评论

          本文标题:6、字典

          本文链接:https://www.haomeiwen.com/subject/ljzhzftx.html