Advertisement

Python字典知识点总结

阅读量:

文章目录

  • 字典(dict)

  • 一、字典的创建

      • 1.1 key-value形式
      • 1.2 dict()转换
        • (1)关键字参数
    • (2)元组、列表
    • (3)字典(不推荐,建议直接写出字典)
    • (4)压缩列表:dict(zip(list1,list2))
  • 1.3 List Comprehensions

  • 1.4 The fromkeys() Method:

  • (1) Note: The fromkeys() method does not affect existing dictionaries

  • (2) It is used to quickly create a dictionary (value elements need to be modified)

    复制代码
    * 1.5 注意:字典key键为不可变数据类型

第二部分:增删改优化方案

  1. 关键字参数设置

  2. 列表形式数据处理

  3. 字典形式数据处理

  • 三、查询(从字典访问元素)
        • 通过 key 访问元素(索引取值):通过按取 key 键可获取 value 值
      • 使用 get 方法访问元素:调用 get 方法以获取对应 value 值
        • 2.1 存在 key 键时
        • 若存在 key 键则可调用 get 方法获取对应 value 值
      • 2.2 若无 key 键存在,则无法直接获取对应 value 值
      • 2.3 若指定 key 的 value 设定为空或无,则返回该默认值

3.setdefault()方法用于获取键对应的值
4.for循环
4.1 items()、keys()、values()的用法
4.2 遍历字典
(1)通过items()遍历字典的所有键值对
(2)使用keys()获取字典的所有键名
(3)调用values()方法获取全部值
(4)结合键与值进行遍历

  • 四、字典中的删除操作
    • 执行指定键值对的删除:通过调用该方法实现指定键值对的移除

      • 删除最后一个键值对:采用该方法可执行最后一条记录的清除操作
      • 删减特定键的操作:使用del指令可实现对应键名的具体删减
      • 删减整个数据结构:采用del指令可一次性清除整个数据对象
      • 完成数据清理过程:调用clear函数将完成当前字典的所有数据清除工作
    • 五、嵌套字典


字典(dict)

作为一种基础的数据结构,在Python中得到了广泛的应用。
为了优化列表中的索引查询效率问题,
为此人们设计出了一种更为直观的数据存储方式,
旨在解决数据存储不够直观的问题,
正是由于这些问题的存在,
在这一背景下字典应运而生。
为了优化列表中的索引查询效率,
一种更为高效的数据组织形式应运而生——字典。
其中最显著的问题在于(例如)
当将一个人的详细信息存储在列表中时,
那么该人的名字、年龄等属性都需要先确定其位置索引,
相比之下,
使用字典可以方便地通过键名快速定位并获取对应的信息,
这种方式不仅提升了查找速度,
而且使得数据的管理更加清晰简洁。


提示:以下是本篇文章正文内容,下面案例可供参考

一、字典的创建

字典具有无序性、可变性和索引功能。
该数据结构支持各种类型的存储能力(不包括键名),其各键值通过冒号: 连接表示,并且各键值间使用逗号分隔;整个数据结构包裹于大括号{}内。

1.1 key-value形式

复制代码
    raw_dict = {'apple':'苹果','orange':'桔子'}
    print(raw_dict)

1.2 dict()转换

(1)关键字参数
复制代码
    raw_dict = dict(one=1, two=2, three=3)
    print(raw_dict)  # {'one': 1, 'two': 2, 'three': 3}
(2)元组、列表
复制代码
    raw_dict = dict((('one', 1), ('two', 2), ('three', 3)))  # 元组
    print(raw_dict) # {'one': 1, 'two': 2, 'three': 3}
    raw_dict = dict([('one', 1), ('two', 2), ('three', 3)])  # 列表
    print(raw_dict) # {'one': 1, 'two': 2, 'three': 3}
(3)字典(不推荐,建议直接写出字典)
复制代码
    raw_dict = dict({'one': 1, 'two': 2, 'three': 3})
    print(raw_dict)  # {'one': 1, 'two': 2, 'three': 3}
(4)压缩列表:dict(zip(list1,list2))

特别注意:在使用zip()函数时,请确保其内部的两个列表必须元素个数一致。现在有一种压缩软件叫做Zip utilities, 它们的文件扩展名通常是*.zip, 你可以通过联想记忆来识别它们的功能。

复制代码
    raw_dict = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
    print(raw_dict)  # {'one': 1, 'two': 2, 'three': 3}

1.3 列表的推导式

复制代码
    raw_dict = {k: v for k, v in [('one', 1), ('two', 2), ('three', 3)]}
    print(raw_dict)  # {'one': 1, 'two': 2, 'three': 3}

1.4 fromkeys()方法:

dict.fromkeys(iterable , set_default_value)

(1)注意:fromkeys()方法,对于已经存在的字典不起作用
  • None字典,不起作用(X)
复制代码
    none_dict = {}
    none_dict.fromkeys('one',1)
    print(none_dict) # {}
  • 修改键值(键名在字典中,不起作用)(X)
复制代码
    d1 = {'apple':'苹果','orange':'桔子'}
    d1.fromkeys('apple','iphone手机')
    print(d1) # {'apple': '苹果', 'orange': '桔子'}
  • 添加键值(键名不在字典中,也不起作用)(X)
复制代码
    d1 = {'apple':'苹果','orange':'桔子'}
    d1.fromkeys('Banana','香蕉')
    print(d1) # {'apple': '苹果', 'orange': '桔子'}
(2)用于快速创建字典(value值需要修改)
  • 字符串

不推荐:

复制代码
    # 空字典
    dict1 = {}
    new_dict = dict1.fromkeys("cd",'默认赋值')
    print(new_dict) # {'c': '默认赋值', 'd': '默认赋值'}
    print(dict1) # {}
    print(type(new_dict)) # <class 'dict'>
    # 非空字典
    dict1 = {'a':'1111','b':'2222'}
    new_dict = dict1.fromkeys('cd','默认赋值')
    print(dict1) # {'a':'1111','b':'2222'}
    print(new_dict) # {'c': '默认赋值', 'd': '默认赋值'}

综上所述,在原有字典中并未发生任何更改(对于其他数据类型而言也是如此),反而是这样的做法会带来问题,请自行验证无需赘述)。

复制代码
    str_dict = dict.fromkeys('abcd', '未赋值')
    print(str_dict)  # {'a': '未赋值', 'b': '未赋值', 'c': '未赋值', 'd': '未赋值'}
  • 列表
复制代码
    li_dict = dict.fromkeys([1, 2, 3], '未赋值')
    print(li_dict)  # {1: '未赋值', 2: '未赋值', 3: '未赋值'}
  • 元组
复制代码
    t_dict = dict.fromkeys(('a', 'b', 'c'), '未赋值')
    print(t_dict)  # {'a': '未赋值', 'b': '未赋值', 'c': '未赋值'}
  • 集合
复制代码
    sets_dict = dict.fromkeys({'name', 'age', 'class'}, '未赋值')
    print(sets_dict)  # {'name': '未赋值', 'age': '未赋值', 'class': '未赋值'}

1.5 注意:字典key键为不可变数据类型

复制代码
    """
    不可变(可哈希)的数据类型:int,str,bool,tuple。
    可变(不可哈希)的数据类型:list,dict,set。
    """
  • 以下数据类型可以作为字典的key键:
复制代码
    d1 = {3.2: '数字'} # 数字
    d2 = {'name': '张三'} # 字符串
    d3 = {True: 1, False: 0} # 布尔型
    d4 = {(1, 2, 3):['a','b','c']} # 元组
  • 以下数据类型不能作为字典的key键:
复制代码
    # d5 = {[1, 2, 3]: ['a','b','c']} # list是可变的,不能作为key
    # d6 = {{1: 2}: ["123","456","789"]} # dict是可变的,不能作为key
    # d7 = {{1, 2, 3}: (4,5,6)} # set是可变的, 不能作为key

二、添加与修改

方法一:索引,添加与修改

键名不存在,则添加 "键值对"到字典中;键名存在,则修改 键对应的value值。

dict_name[key] = new_value

复制代码
    dict1 = {'name':'张三','age':18}
    # 添加
    dict1['id'] = 2021001
    print(dict1) # {'name': '张三', 'age': 18, 'id': 2021001}
    # 修改
    dict1['name'] = "李四"
    print(dict1) # {'name': '李四', 'age': 18, 'id': 2021001}

方法二:setdefault()方法:只添加

setdefault()方法还可以查询 功能。

复制代码
    dict2 = {}
    # 能添加
    dict2.setdefault('id','2021')
    print(dict2) # {'id': '2021'}
    # 不能修改
    dict2.setdefault('id','2020') # 再次对相同的key键名操作,不能修改其value值
    print(dict2) # {'id': '2021'}

setdefault()有返回值:

复制代码
    info_dict = {'id':20210001,'name':'张三','age':19}
    id_value = info_dict.setdefault('id')
    print(id_value) # 20210001,返回对应的value值

方法三:update()方法,添加与修改

建议:在处理少量数据时,“方法一”通过索引赋值的方式能够满足需求;而update()方法则特别适合进行大量增删操作;当然,在需要处理少量数据的情况下也可以选择update()方法,并根据个人偏好做出选择。

1.关键字参数

注意:此方法在调用update()方法时应当避免让关键字参数(即键名)带有引号;若关键字参数(即键名)被赋予了引号,则将被视为一个表达式形式,在程序运行过程中会导致错误信息出现。

  • 添加
复制代码
    info_dict = {'name':'张三','age':19}
    info_dict.update(tel=10086) # tel关键参数不能带引号
    print(info_dict) # {'name': '张三', 'age': 19, 'tel': 10086}
  • 修改
复制代码
    info_dict = {'name':'张三','age':19}
    info_dict.update(name='李四') # name关键参数不能带引号
    print(info_dict) # {'name': '李四', 'age': 19}
2.添加或修改,列表
  • 添加
复制代码
    info_dict = {'name': '张三', 'age': 19}
    info_dict.update([('a',1),('b',2)])
    print(info_dict) # {'name': '张三', 'age': 19, 'a': 1, 'b': 2}
  • 修改
复制代码
    info_dict = {'name': '张三', 'age': 19}
    info_dict.update([('name','老王'),('age',32)])
    print(info_dict) # {'name': '老王', 'age': 32}
3.添加或修改,字典
  • 添加
复制代码
    info_dict = {'姓名': '小天使', '年龄': 20}
    info_dict.update({'身高': '1.75', '体重': 90})
    print(info_dict) # {'姓名': '小天使', '年龄': 20, '身高': '1.75', '体重': 90}
  • 修改
复制代码
    info_dict = {'姓名': '小天使', '年龄': 28}
    info_dict.update({'姓名':'小恶魔'})
    print(info_dict) # {'姓名': '小恶魔', '年龄': 28}

三、查询(从字典访问元素)

1.使用 key 访问元素(索引取值):即按key键获取value值

复制代码
    info_dict = {'name':'张三','age':19}
    print(info_dict['name']) # 张三

2.使用get()访问元素:获取key键对应的value值

2.1 存在key键时
复制代码
    info_dict = {'name':'张三','age':19}
    value = info_dict.get('name') # 存在key键
    print('name =',value) # name = 张三
2.2 不存在key键时
复制代码
    info_dict = {'name':'张三','age':19}
    value = info_dict.get('a') # 不存在key键
    print('name =',value) # name = None
2.3 设置指定键的值不存在时,返回该默认值
复制代码
    info_dict = {'name':'张三','age':19}
    value = info_dict.get('a','找不到该键')
    print('name =',value) # name = 找不到该键

3.setdefault()方法:查询值

setdefault()方法还可以添加 新键值到字典中。

复制代码
    info_dict = {'name':'张三','age':19,'address':'广州'}
    name = info_dict.setdefault('name')
    print(name) # 张三

4.for循环

4.1 items(),keys(),values()的用法
复制代码
    info_dict = {'name':'张三','age':19,'address':'广州'}
    
    # 查询/获取字典所有键值对
    print(info_dict.items()) # dict_items([('name', '张三'), ('age', 19), ('address', '广州')])
    print(list(info_dict.items())) # [('name', '张三'), ('age', 19), ('address', '广州')]
    
    # 查询/获取字典所有键
    print(info_dict.keys()) # dict_keys(['name', 'age', 'address'])
    print(list(info_dict.keys())) # ['name', 'age', 'address']
    
    # 查询/获取字典所有值
    print(info_dict.values()) # dict_values(['张三', 19, '广州'])
    print(list(info_dict.values())) # ['张三', 19, '广州']
4.2 遍历字典
(1)遍历字典所有键值对:items()
复制代码
    info_dict = {
    'id':202101,
    'name':'张三',
    'age':19
    }
    for item in info_dict.items():
    print(item)
    """输出
    ('id', 202101)
    ('name', '张三')
    ('age', 19)
    """
(2)遍历字典所有键名:keys()
复制代码
    info_dict = {
    'id':202101,
    'name':'张三',
    'age':19
    }
    for key in info_dict.keys():
    print(key)
    """输出
    id
    name
    age
    """
(3)遍历字典所有值:values()
复制代码
    info_dict = {
    'id':202101,
    'name':'张三',
    'age':19
    }
    for value in info_dict.values():
    print(value)
    """输出
    202101
    张三
    19
    """
(4)遍历字典的键与值
复制代码
    info_dict = {
    'id':202101,
    'name':'张三',
    'age':19
    }
    for k,v in info_dict.items():
    print(k,v)
    """输出
    id 202101
    name 张三
    age 19
    """

四、字典中的删除操作

1.pop(key):移除指定key键的key-value键值对

复制代码
    infoDict = {
    'id': 2021001,
    'name': '张三',
    'age': 19,
    'address': '广东广州',
    'tel': 15699998888
    }
    age = infoDict.pop('age')
    # 查看移除的值
    print(age)  # 19
    # 查看字典的情况
    print(infoDict) # {'id': 2021001, 'name': '张三', 'address': '广东广州', 'tel': 15699998888}

2.popitem():删除最后一个key-value键值对

复制代码
    infoDict = {
    'id': 2021001,
    'name': '张三',
    'age': 19,
    'address': '广东广州',
    'tel': 15699998888
    }
    pop_keyValue = infoDict.popitem()  # 删除最后一个键值对
    print(pop_keyValue)  # ('tel', 15699998888)
    print(infoDict) # {'id': 2021001, 'name': '张三', 'age': 19, 'address': '广东广州'}

3.del dict_name[key]:删除指定key键

复制代码
    infoDict = {
    'id': 2021001,
    'name': '张三',
    'age': 19,
    'address': '广东广州',
    'tel': 15699998888
    }
    del infoDict['address']  # 删除指定键名对应的键值对
    print(infoDict) # {'id': 2021001, 'name': '张三', 'age': 19, 'tel': 15699998888}

4.del dict_name:删除整个字典

复制代码
    infoDict = {
    'id': 2021001,
    'name': '张三',
    'age': 19,
    'address': '广东广州',
    'tel': 15699998888
    }
    del infoDict
    # print(infoDict) 报错,字典不存在,不能打印

5.clear():清空字典

复制代码
    infoDict = {
    'id': 2021001,
    'name': '张三',
    'age': 19,
    'address': '广东广州',
    'tel': 15699998888
    }
    infoDict.clear()
    print(infoDict)  # {}

五、嵌套字典

复制代码
    info_dict = {
    '姓名': '张三',
    '年龄': 20,
    '出生地': '广东广州',
    '国籍': '中国',
    '兴趣': ['打篮球', '踢足球', '打兵乓球'],
    '社交': {'qq': 'qq10086', '微信': 'vx10010', '知乎': 'zw10000'},
    '读过的书籍': {'语言类': ['汉语言文学', '对外汉语', '中国少数民族语言文学'], '理工类': ['材料化学', '软件工程', '生物科学']},
    }
    # 获取张三的名字:
    print(info_dict['姓名'])
    # 获取的兴趣下的踢足球:
    print(info_dict['兴趣'][1])
    # 获取社交的qq号:
    print(info_dict['社交']['qq'])
    # 获取汉语言文学
    print(info_dict['读过的书籍']['语言类'][0])
    # 获取软件工程
    print(info_dict['读过的书籍']['理工类'][1])

全部评论 (0)

还没有任何评论哟~