• Python组合数据类型——映射类型:字典


    在这里插入图片描述

    🤵‍♂️ 个人主页: @Flyme awei 个主页
    👨‍💻 作者简介:Python领域新星创作者。
    📒 系列专栏:《在线编程-Python篇
    🌐 推荐一款找工作神器网站: 《牛客网》 |笔试题库|面试经验|
    🐋 希望大家多多支持😘一起进步呀!
    📝 如果文章对你有帮助的话,欢迎评论💬点赞👍收藏📂加关注

    前言

      今天是《CSDN21天学习挑战赛》的第9天
      昨天学习了Python组合数据类型——序列类型:列表、元组
      今天将学习Python组合数据类型——映射类型:字典。

    活动地址:CSDN21天学习挑战赛

    1、字典类型

    1.1什么是字典

    字典:Python内置的数据结构之一,与列表一样是一个可变序列,以键值对的方式存储数据,字典是一个无序的序列Python语言中的字典使用大括号{ }建立,每个元素是一个键值对。

    键值对”是组织数据的一种重要方式,广泛应用在当代大型信息系统中,如Web系统。键值对的基本思想是将“值”信息关联一个“键”信息,进而通过键信息找对应的值信息,这个过程叫映射。Python语言中通过字典类型实现映射。

    1.2字典示意图

    在这里插入图片描述

    1.3字典的原理

    字典的原理:Python中的字典是根据key查找value所在的位置

    1.4创建字典的方式

    python中创建一个字典对象,常用的方式有两种。

    1. 第一种方式,使用花括号{ }
    '''
    第一种方式,使用花括号{},语法如下所示
    使用{}创建字典
    scores = {'张三': 100, '李四': 98, '王五': 45}
    '''
    scores = {'张三': 29, '李四': 10, '王五': 40}
    print(scores)  # {'张三': 29, '李四': 10, '王五': 40}
    print(type(scores))  # 
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 第二种方式,使用内置函数dict()
    '''第二种方式,使用内置函数dict()。dict即dictionary(字典)的缩写,语法如下所示。
    字典名 = dict(键1=值1, 键2=值2)
    '''
    dic = dict(name='张三', age=20)
    print(dic)  # {'name': '张三', 'age': 20}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. 创建空字典
    d = {}
    print(d)  # {}
    
    • 1
    • 2

    1.5字典元素的获取

    根据键key获取字典的值value

    # 1.使用 [] 获取
    scores = {'张三': 29, '李四': 10, '王五': 40}
    print('张三' in scores)  # True
    print('张三' not in scores)  # False
    print(scores['张三'])  # 29
     
    # 2.使用 get()方法
    print(scores.get('张三'))  # 29
    print(scores.get('柽柳'))   # None
    print(scores.get('麻子', 99))  # 99是在查找 麻子值的(value)不存在时的一个默认值
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、字典类型的操作

    2.1字典的操作函数

    Python内置数据结构:字典dict()类源代码:

    class dict(object):
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        """
        def clear(self): # real signature unknown; restored from __doc__
            """ D.clear() -> None.  Remove all items from D. """
            pass
    
        def copy(self): # real signature unknown; restored from __doc__
            """ D.copy() -> a shallow copy of D """
            pass
    
        @staticmethod # known case
        def fromkeys(*args, **kwargs): # real signature unknown
            """ Create a new dictionary with keys from iterable and values set to value. """
            pass
    
        def get(self, *args, **kwargs): # real signature unknown
            """ Return the value for key if key is in the dictionary, else default. """
            pass
    
        def items(self): # real signature unknown; restored from __doc__
            """ D.items() -> a set-like object providing a view on D's items """
            pass
    
        def keys(self): # real signature unknown; restored from __doc__
            """ D.keys() -> a set-like object providing a view on D's keys """
            pass
    
        def pop(self, k, d=None): # real signature unknown; restored from __doc__
            """
            D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
            If key is not found, d is returned if given, otherwise KeyError is raised
            """
            pass
    
        def popitem(self, *args, **kwargs): # real signature unknown
            """
            Remove and return a (key, value) pair as a 2-tuple.
            
            Pairs are returned in LIFO (last-in, first-out) order.
            Raises KeyError if the dict is empty.
            """
            pass
    
        def setdefault(self, *args, **kwargs): # real signature unknown
            """
            Insert key with a value of default if key is not in the dictionary.
            
            Return the value for key if key is in the dictionary, else default.
            """
            pass
    
        def update(self, E=None, **F): # known special case of dict.update
            """
            D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
            If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
            If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
            In either case, this is followed by: for k in F:  D[k] = F[k]
            """
            pass
    
        def values(self): # real signature unknown; restored from __doc__
            """ D.values() -> an object providing a view on D's values """
            pass
    
        def __contains__(self, *args, **kwargs): # real signature unknown
            """ True if the dictionary has the specified key, else False. """
            pass
    
        def __delitem__(self, *args, **kwargs): # real signature unknown
            """ Delete self[key]. """
            pass
    
        def __eq__(self, *args, **kwargs): # real signature unknown
            """ Return self==value. """
            pass
    
        def __getattribute__(self, *args, **kwargs): # real signature unknown
            """ Return getattr(self, name). """
            pass
    
        def __getitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__getitem__(y) <==> x[y] """
            pass
    
        def __ge__(self, *args, **kwargs): # real signature unknown
            """ Return self>=value. """
            pass
    
        def __gt__(self, *args, **kwargs): # real signature unknown
            """ Return self>value. """
            pass
    
        def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
            """
            dict() -> new empty dictionary
            dict(mapping) -> new dictionary initialized from a mapping object's
                (key, value) pairs
            dict(iterable) -> new dictionary initialized as if via:
                d = {}
                for k, v in iterable:
                    d[k] = v
            dict(**kwargs) -> new dictionary initialized with the name=value pairs
                in the keyword argument list.  For example:  dict(one=1, two=2)
            # (copied from class doc)
            """
            pass
    
        def __iter__(self, *args, **kwargs): # real signature unknown
            """ Implement iter(self). """
            pass
    
        def __len__(self, *args, **kwargs): # real signature unknown
            """ Return len(self). """
            pass
    
        def __le__(self, *args, **kwargs): # real signature unknown
            """ Return self<=value. """
            pass
    
        def __lt__(self, *args, **kwargs): # real signature unknown
            """ Return self
            pass
    
        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass
    
        def __ne__(self, *args, **kwargs): # real signature unknown
            """ Return self!=value. """
            pass
    
        def __repr__(self, *args, **kwargs): # real signature unknown
            """ Return repr(self). """
            pass
    
        def __reversed__(self, *args, **kwargs): # real signature unknown
            """ Return a reverse iterator over the dict keys. """
            pass
    
        def __setitem__(self, *args, **kwargs): # real signature unknown
            """ Set self[key] to value. """
            pass
    
        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ D.__sizeof__() -> size of D in memory, in bytes """
            pass
    
        __hash__ = None
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159

    字典类型的一些通用操作函数

    操作函数描述
    dict()生成一个字典
    len(d)字典d元素的个数(长度)
    min(d)字典d中键的最最小值
    max(d)字典d中键的最最大值

    2.2字典的操作方法

    字典类型有一些操作方法,使用的语法格式为:
    <字典对象名>.<方法名>(<方法参数>)

    操作方法描述
    d.keys()返回字典d所有键的信息
    d.values()返回字典d所有值的信息
    d.items()返回字典d所有键值对
    d.get(key, default)键存在则返回相应值,否则返回默认值default
    d.pop(key, default)键存在则返回相应值,同时删除键值对,否则返回默认值default
    d.popitem()随机从字典中取出一个兼职对,以元组(key, value)的形式返回,同时将该键值对从字典中删除。
    d.clear()删除所有的键值对,清空字典

    2.3字典元素的增删改操作

    scores = {'张三': 29, '李四': 10, '王五': 40}

    • key的判断
    # key的判断
    scores = {'张三': 29, '李四': 10, '王五': 40}
    print('张三' in scores)  # True
    print('张三' not in scores)  # True
    
    • 1
    • 2
    • 3
    • 4
    • 字典的删除
    # 字典元素的删除
    del scores['张三']  # 删除指定的键值对
    print(scores)  # {'李四': 10, '王五': 40}
    
    
    • 1
    • 2
    • 3
    • 4
    • 字典的清除
    # 清空字典 clear()方法
    scores.clear()
    print(scores)  # {}
    
    
    • 1
    • 2
    • 3
    • 4
    • 字典元素的新增
    # 新增元素
    scores['陈六'] = 20
    print(scores)  # {'陈六': 20}
    
    
    • 1
    • 2
    • 3
    • 4
    • 字典元素值的修改
    # 修改value
    scores['陈六'] = 100
    print(scores)  # {'陈六': 100}
    
    
    • 1
    • 2
    • 3
    • 4

    2.4字典视图的获取

    • 获取所有的键, <字典对象名>.keys()方法 返回值为列表
    # 获取所有的键 .keys()方法 返回值为列表
    scores = {'张三': 29, '李四': 10, '王五': 40}
    print(scores.keys())  # dict_keys(['张三', '李四', '王五'])
    print(type(scores.keys()))  # 
    print(list(scores.keys()))  # ['张三', '李四', '王五']
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 获取所有的值,<字典对象名>.value()方法,返回值为列表
    # 获取所有的值 <字典对象名>.value()方法 返回值为列表
    dict_values = scores.values()
    print(dict_values)  # dict_values([29, 10, 40])
    print(type(dict_values))  # 
    print(list(dict_values))  # [29, 10, 40]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 获取所有的键值对,<字典对象名>.items()方法 返回值为元组
    #  获取所有的键值对  返回值为元组
    print(scores.items())
    # dict_items([('张三', 29), ('李四', 10), ('王五', 40)])
    
    • 1
    • 2
    • 3

    2.5字典元素的遍历

    字典元素的遍历:使用for-in循环

    # 字典元素的遍历
    scores = {'张三': 29, '李四': 10, '王五': 40}
    for item in scores:
        print(item, scores[item])
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    3、字典的特点

    1.键 key 不可以重复,值value可以重复

    2.字典中元素是无序的

    3.字典会浪费大的内存,是一种使用空间换时间的数据结构,但是查询速度快。

    4、字典生成式

    • 内置函数zip()

    用于将可迭代对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表

    • 字典生成式:
      {key: value for key, value in zip(items,prices)}
    items = ['Fruits', 'Books', 'Others']  # 键的列表
    prices = [96, 78, 85]  # 值的列表
    d = {items: prices for items, prices in zip(items, prices)}  # 两个列表生成一个字典
    print(d)  # {'Fruits': 96, 'Books': 78, 'Others': 85}
    
    # .upper()方法 键字母变大写
    d = {items.upper(): prices for items, prices in zip(items, prices)}  # 两个列表生成一个字典
    print(d)  # {'Fruits': 96, 'Books': 78, 'Others': 85}
    
    
    items = ['Fruits', 'Books', 'Others']  # 键的列表
    prices = [96, 78, 85]  # 值的列表
    a = dict(zip(items, prices))
    print(a)  # {'Fruits': 96, 'Books': 78, 'Others': 85}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述

    5、总结

    字典类型的一些通用操作函数:

    操作函数描述
    dict()生成一个字典
    len(d)字典d元素的个数(长度)
    min(d)字典d中键的最最小值
    max(d)字典d中键的最最大值

    字典类型有一些操作方法:

    操作方法描述
    d.keys()返回字典d所有键的信息
    d.values()返回字典d所有值的信息
    d.items()返回字典d所有键值对
    d.get(key, default)键存在则返回相应值,否则返回默认值default
    d.pop(key, default)键存在则返回相应值,同时删除键值对,否则返回默认值default
    d.popitem()随机从字典中取出一个兼职对,以元组(key, value)的形式返回,同时将该键值对从字典中删除。
    d.clear()删除所有的键值对,清空字典
  • 相关阅读:
    高等数学基础概念的Python开发实现
    【PlasticSCM Could Edition】新版本云托管浅试 (与踩一些坑)
    线程的概念
    采集数据工具推荐,以及采集数据列表详细图解流程
    Springboot框架中使用 Redis + Lua 脚本进行限流功能
    【跟小嘉学 Rust 编程】二十八、Rust中的日期与时间(DateTime)
    前端知识大全之HTML
    JAVA面试技术栈
    Centos7防火墙相关命令
    R语言dplyr包intersect函数获取在两个dataframe中都存在的数据行、获取两个dataframe交叉的数据行
  • 原文地址:https://blog.csdn.net/m0_68744965/article/details/126246290