python dictionay(字典 )基本用法

时间:2023-03-09 14:43:00
python dictionay(字典 )基本用法
  • dict(dictionary)是一系列无序对象的集合,由键-值对构成,通过读取键来取得对应的值,具有可变,无序,异构,可嵌套的属性。
  • dict初始化
    1、直接采用字典格式
    python dictionay(字典 )基本用法

    2、利用dict(),[注]:键没有加''
    python dictionay(字典 )基本用法

    3、利用tuple(元组)
    python dictionay(字典 )基本用法

    4、使用dict.fromkeys(),返回字典,该方法有两个参数,参数1为键列表,参数2为这些键的初始值,默认为空
    python dictionay(字典 )基本用法

  • dict添加、删除、修改

    1、键如果不存在则添加键-值,如果存在则修改键-值
    python dictionay(字典 )基本用法

    2、删除指定的键-值对
    python dictionay(字典 )基本用法

    3、删除指定的键-值,返回删除键的值,如果指定的键不存在则返回None
    python dictionay(字典 )基本用法

    4、删除整个字典的键-值
    python dictionay(字典 )基本用法

    5、使用dict.update()更新字典,如果键相同则更新,如果键不存在则添加
    python dictionay(字典 )基本用法

    6、使用dict.setdefault()设置键的默认值,返回值。如果键存在,返回该键的原值;如果键不存在,则添加键-值,返回该值
    python dictionay(字典 )基本用法

  • dict的查询

    1、指定键
    python dictionay(字典 )基本用法

    2、使用dict.items()方法,返回所有键-值对(items)列表,键-值对以tuple(元组)形式表示
    python dictionay(字典 )基本用法

    3、使用dict.keys()方法,返回所有的键的列表
    python dictionay(字典 )基本用法

    4、使用dict.values()方法,返回所有键的值的列表
    python dictionay(字典 )基本用法

    5、使用for循环遍历字典
    python dictionay(字典 )基本用法

    6、使用dict.get()方法,如果指定的键存在,则返回该键的智,如果不存在,则返回参数中给定的值(第二个参数)
    python dictionay(字典 )基本用法

    7、使用len(),返回字典中键-值对的个数
    python dictionay(字典 )基本用法

    8、使用dict.has_key(),如果键存在返回True,如果键不存在返回False(python3.x没有dict.has_key())
    python dictionay(字典 )基本用法

  • dict其他常用方法

    1、使用copy.copy()浅拷贝
    python dictionay(字典 )基本用法

    2、使用copy.deepcopy()深拷贝
    python dictionay(字典 )基本用法

    3、使用dict.copy()浅拷贝
    python dictionay(字典 )基本用法