• 字典


    为什么要设立字典

    1. 列表如果存储大量数据,查询速度比较慢

    2. 列表的数据没有关联性

    由于列表具有以上缺点,因此python引入了一种新的数据类型:字典

    字典是一种可变的数据类型,这里补充一下python数据类型分类,python数据类型按照不同的标准可分为:可变与不可变;容器与非容器;

    什么是字典

    字典是python里唯一一种映射类型,采用键值对的结构来存储数据,形式为: {key1: value1,key2: value2}

    1. 字典的键必须是可hash的数据类型,键是唯一的,不能重复;字典的值可以是任意的数据类型

    2. 字典的键可以通过hash算法映射成内存地址,因此字典的查询速度非常快

    3. 字典在3.5之前(包括3.5)是无序的,3.6以后的版本按照创建字典的顺序排列

    字典的创建

    1 dic1 = {}
    2 dic2 = dict()
    3 print(type(dic1))
    4 print(type(dic2))

    输出

    <class 'dict'>
    <class 'dict'>
    
    Process finished with exit code 0

    注意:

    (1){}表示创建字典而不是集合;

    (2)dict()的创建是小括号而不是大括号,表示实例化一个字典对象

    小结

    字典的几种创建方式:

    1. dic = {"name": "Ara", "age": 18}

    2. dic = dict()

      dic = dict({"name": "Ara", "age": 18})

      dic = dict(name="Ara", age=18)

    3. dic.fromkeys("abc", "123")

    4. dic = [[1, "a"], [2, "b"], [3, "c"]]   # 子列表或元组的长度必须是2

        dic = ((1, "a"), (2, "b"), (3, "c"))

    字典的增删改查

    1. 增

    按照索引添加

    有则覆盖,无则创建

    1 dic = {1: "a", 2: "b", 3: "c"}
    2 dic[1] = "A"
    3 print(dic)
    4 dic[4] = "d"
    5 print(dic)

    输出

    {1: 'A', 2: 'b', 3: 'c'}
    {1: 'A', 2: 'b', 3: 'c', 4: 'd'}
    
    Process finished with exit code 0

    setdefault 添加

    有则不变,无则创建

    1 dic = {1: "a", 2: "b", 3: "c"}
    2 dic.setdefault(2, "B")
    3 print(dic)
    4 dic.setdefault(4, "d")
    5 print(dic)

    输出

    {1: 'a', 2: 'b', 3: 'c'}
    {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
    
    Process finished with exit code 0

    2. 删

    pop

    dic.pop(k,a)   删除k对应的键值对,返回删除的值(注意只有值,而不是键值对,pop必须指定索引

    删除k,如果没有此键就返回a,如果不设置a找不到k会报错

    1 dic = {1: "a", 2: "b", 3: "c"}
    2 print(dic.pop(4))
    3 print(dic)

    输出

    Traceback (most recent call last):
      File "D:/字典.py", line 30, in <module>
        print(dic.pop(4))
    KeyError: 4
    
    Process finished with exit code 1

    设置k和 a

    1 dic = {1: "a", 2: "b", 3: "c"}
    2 print(dic.pop(2, "没有此键"))
    3 print(dic)
    4 print(dic.pop(4, "没有此键"))
    5 print(dic)

    输出

    b
    {1: 'a', 3: 'c'}
    没有此键
    {1: 'a', 3: 'c'}
    
    Process finished with exit code 0

    clear

    dic.clear()   清空字典

    1 dic = {1: "a", 2: "b", 3: "c"}
    2 dic.clear()
    3 print(dic)

    输出

    {}
    
    Process finished with exit code 0

    popitem 

    删除最后一个键值对,以元组的形式返回删除的键值对,3.5之前是随机删除,3.6之后是删除最后一个,只能删除最后一个,不能选定k来删除

    1 dic = {1: "a", 2: "b", 3: "c"}
    2 print(dic.popitem())
    3 print(dic)

    输出

    (3, 'c')
    {1: 'a', 2: 'b'}
    
    Process finished with exit code 0

    del

    del dic1  删除整个字典

    1 dic = {1: "a", 2: "b", 3: "c"}
    2 del dic
    3 print(dic)

    输出

    Traceback (most recent call last):
      File "D:/字典.py", line 44, in <module>
        print(dic)
    NameError: name 'dic' is not defined
    
    Process finished with exit code 1

    注意清空是删除字典里的元素,字典还在,删除是彻底删除整个字典,回收其内存空间

    del也可以按照键来删,格式为del dic[key]

    1 dic = {"name": "王大锤", "age": 18, "hobby": "吹牛"}
    2 del dic["age"]
    3 print(dic)

    输出

    {'name': '王大锤', 'hobby': '吹牛'}
    
    Process finished with exit code 0

    3. 改

    update

    dic2.update(dic1)   将dic1的数据覆盖添加到dic2中(原来有的就覆盖,没有就添加)

    1 dic1 = {1: "a", 2: "b", 3: "c"}
    2 dic2 = {1: "A", 3: "c", "name": "夏洛", "age": "18", "hometown": "西红柿"}
    3 dic1.update(dic2)
    4 print(dic1)

    输出

    {1: 'A', 2: 'b', 3: 'c', 'name': '夏洛', 'age': '18', 'hometown': '西红柿'}
    
    Process finished with exit code 0

    dic2.update(name="", )  关键字参数更改

    1 dic1 = {1: "a", 2: "b", 3: "c", "name": "夏洛", "age": "18", "hometown": "西红柿"}
    2 dic1.update(name="马冬梅", hometown="西虹市")
    3 print(dic1)

    输出

    {1: 'a', 2: 'b', 3: 'c', 'name': '马冬梅', 'age': '18', 'hometown': '西虹市'}
    
    Process finished with exit code 0

     按照索引改

    按照索引找到然后赋值

    4. 查

    按照键查对应的值,找不到键会报错

    1 dic1 = {1: "a", 2: "b", 3: "c", "name": "夏洛", "age": "18", "hometown": "西红柿"}
    2 print(dic1["name"])
    3 print(dic1["d"])

    输出

    Traceback (most recent call last):
    夏洛
      File "D:/字典.py", line 58, in <module>
        print(dic1["d"])
    KeyError: 'd'
    
    Process finished with exit code 1

    get

    dic.get(key, a)  找不到key就返回设定的值a

    1 dic1 = {1: "a", 2: "b", 3: "c", "name": "夏洛", "age": "18", "hometown": "西红柿"}
    2 print(dic1.get(3, -1))
    3 print(dic1.get(4, -1))
    4 print(dic1.get(4, "未找到此键"))

    输出

    c
    -1
    未找到此键
    
    Process finished with exit code 0

    循环遍历

    (1)直接循环(获取的是key)

    for i in dic:

        print(i)

    (2)在dic.keys里循环

    for i in dic.keys():

        print(i)       # 打印key

    (3)在dic.values()里循环

    for i in dic.values():

        print(i)       # 打印value

    (4)在dic.items()里循环  

    for i in dic.items():    

        print(i)       # 打印键值对

    for k, v in dic.items():

        print(k)     # 打印键

    这里有一个小知识点-----分别赋值(复合赋值)

    用yi

    5. fromkeys()创建字典

    将一个可迭代对象的元素作为key创建字典(值都一样)

    1 dic1 = dict.fromkeys("hello", "$$$")
    2 print(dic1)
    3 dic2 = dict.fromkeys([1, 2, 3], "$$$")
    4 print(dic2)

    输出

    {'h': '$$$', 'e': '$$$', 'l': '$$$', 'o': '$$$'}
    {1: '$$$', 2: '$$$', 3: '$$$'}
    
    Process finished with exit code 0

    当值是可变数据类型时,通过fromkeys创建的字典的值是同一个内存地址

    1 dic3 = dict.fromkeys("123", ["a", "b", "c"])
    2 print(dic3)
    3 dic3["3"].append("d")
    4 print(dic3)

    输出

    {'1': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '3': ['a', 'b', 'c']}
    {'1': ['a', 'b', 'c', 'd'], '2': ['a', 'b', 'c', 'd'], '3': ['a', 'b', 'c', 'd']}
    
    Process finished with exit code 0

    可以看到上述通过fromkeys创建的字典里面的的列表是指向同一个内存地址的,一个发生改变,其余的也跟着改变

    字典用于格式化输出 

    之前学的字符串用于格式化输出的有%s和format,我们回顾一下用法

    1 msg = "我叫%s,今年%s, 爱好%s" % ("王大锤", 18, "吹牛")
    2 print(msg)
    3 
    4 msg = "我叫{},今年{}, 爱好{}".format("王大锤", 18, "吹牛")
    5 print(msg)
    6 
    7 msg = "我叫{name},今年{age}, 爱好{hobby}".format(name="王大锤", age=18, hobby="吹牛")
    8 print(msg)

    输出

    我叫王大锤,今年18, 爱好吹牛
    我叫王大锤,今年18, 爱好吹牛
    我叫王大锤,今年18, 爱好吹牛
    
    Process finished with exit code 0

    利用字典也可以实现类似的功能,;来看代码

    1 dic = {"name": "王大锤", "age": 18, "hobby": "吹牛"}
    2 msg = "我叫%(name)s,今年%(age)s, 爱好%(hobby)s" % dic   # 把占位符后面括号里的键换成对应的值,形成格式化输出
    3 print(msg)

    输出

    我叫王大锤,今年18, 爱好吹牛
    
    Process finished with exit code 0
  • 相关阅读:
    Django MVC与MTV概念 Ajax、分页实现
    Django F查询Q查询Only与Defel
    Django ORM 操作
    已有数据的表添加自增主键
    java随机字符串+校验位
    mysql日志触发器
    dad
    jsp自定义标签
    php-pfm指定配置文件
    type
  • 原文地址:https://www.cnblogs.com/zzliu/p/10173153.html
Copyright © 2020-2023  润新知