• 【python】python中字典的用法记录


    序言

    • 总结字典的一些常见用法

    1. 字典的创建和访问

    • 字典是一种可变容器类型,可以存储任意类型对象

    • key : value,其中value可以是任何数据类型,key必须是不可变的如字符串、数字、元组,不可以用列表

    • key是唯一的,如果出现两次,后一个值会被记住

    • 字典的创建

      • 创建空字典

        dictionary = {}
        
        • 1
      • 直接赋值创建字典

        dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175}
        
        • 1
      • 通过关键字dict和关键字参数创建字典

        dictionary = dict(name='Nick', age=20, height=175)
        
        • 1
        dictionary = dict()
        for i in range(1, 5):
            dictionary[i] = i * i
        print(dictionary)		# 输出结果:{1: 1, 2: 4, 3: 9, 4: 16}
        
        • 1
        • 2
        • 3
        • 4
      • 通过关键字dict和二元组列表创建

        my_list = [('name', 'Nick'), ('age', 20), ('height', 175)]
        dictionary = dict(my_list)
        
        • 1
        • 2
      • 通过关键字dict和zip创建

        dictionary = dict(zip('abc', [1, 2, 3]))
        print(dictionary)	# 输出{'a': 1, 'b': 2, 'c': 3}
        
        • 1
        • 2
      • 通过字典推导式创建

        dictionary = {i: i ** 2 for i in range(1, 5)}
        print(dictionary)	# 输出{1: 1, 2: 4, 3: 9, 4: 16}
        
        • 1
        • 2
      • 通过dict.fromkeys()来创建

        dictionary = dict.fromkeys(range(5), 'x')
        print(dictionary)		# 输出{0: 'x', 1: 'x', 2: 'x', 3: 'x'}
        
        • 1
        • 2

        这种方法用来初始化字典设置value的默认值

    • 字典的访问

      • 通过键值对访问

        dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175}
        print(dictionary['age'])
        
        • 1
        • 2
      • 通过dict.get(key, default=None)访问:default为可选项,指定key不存在时返回一个默认值,如果不设置默认返回None

        dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}
        print(dictionary.get(3, '字典中不存在键为3的元素'))
        
        • 1
        • 2
      • 遍历字典的items

        dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}
        print('遍历输出item:')
        for item in dictionary.items():
            print(item)
        
        print('\n遍历输出键值对:')
        for key, value in dictionary.items():
            print(key, ' : ', value)
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
      • 遍历字典的keys或values

        dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}
        
        print('遍历keys:')
        for key in dictionary.keys():
            print(key)
        
        print('\n通过key来访问:')
        for key in dictionary.keys():
            print(dictionary[key])
        
        print('\n遍历value:')
        for value in dictionary.values():
            print(value)
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
      • 遍历嵌套字典

        for key, value in dict_2.items():
            if type(value) is dict:				# 通过if语句判断value是不是字典
                for sub_key, sub_value in value.items():
                    print(sub_key, "→", sub_value)
        
        • 1
        • 2
        • 3
        • 4

    2. 字典如何添加元素

    • 使用[]

      dictionary = {}
      dictionary['name'] = 'Nick'
      dictionary['age'] = 20
      dictionary['height'] = 175
      print(dictionary)
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • 使用update()方法

      dictionary = {'name': 'Nick', 'age': 20, 'height': 175}
      dictionary.update({'age' : 22})         # 已存在,则覆盖key所对应的value
      dictionary.update({'2' : 'tetst'})      # 不存在,则添加新元素
      print(dictionary)
      
      • 1
      • 2
      • 3
      • 4

    3. 字典作为函数参数

    • 字典作为参数传递时:函数内对字典修改,原来的字典也会改变

      dictionary = {'name': 'Nick', 'age': 20, 'height': 175}
      dictionary.update({'age': 22})  # 已存在,则覆盖key所对应的value
      dictionary.update({'2': 'test'})  # 不存在,则添加新元素
      print(dictionary)
      
      
      def dict_fix(arg):
          arg['age'] = 24
      
      
      dict_fix(dictionary)
      
      print(dictionary)	# age : 24
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
    • 字典作为可变参数时:函数内对字典修改,不会影响到原来的字典

      dictionary = {'name': 'Nick', 'age': 20, 'height': 175}
      dictionary.update({'age': 22})  # 已存在,则覆盖key所对应的value
      dictionary.update({'2': 'test'})  # 不存在,则添加新元素
      print(dictionary, '\n')
      
      
      def dict_fix(**arg):
          for key, value in arg.items():
              print(key, '->', value)	# age : 22
          arg['age'] = 24
      
      
      dict_fix(**dictionary)
      
      print('\n', dictionary)	# age : 22
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
    • 关于字典作为**可变参数时的key类型说明

      dictionary = {}
      dictionary.update({2: 'test'})
      print(dictionary, '\n')
      
      
      def dict_fix(**arg):
          for key, value in arg.items():
              print(key, '->', value)
          arg['age'] = 24
      	
      dict_fix(**dictionary)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 报错:TypeError: keywords must be strings,意思是作为**可变参数时,key必须是string类型
      • 作为普通参数传递则不存在这个问题
      dictionary = {}
      dictionary.update({2: 'test'})
      print(dictionary, '\n')
      
      
      def dict_fix(arg):
          for key, value in arg.items():
              print(key, '->', value)
          arg['2'] = 'new'
      
      
      dict_fix(dictionary)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
    • 补充一个例子

      def function(*a,**b):
          print(a)
          print(b)
      a=3
      b=4
      function(a, b, m=1, n=2)	# (3, 4) {'n': 2, 'm': 1}
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 对于不使用关键字传递的变量,会被作为元组的一部分传递给*a,而使用关键字传递的变量作为字典的一部分传递给了**b

    4. 字典排序

    • 使用python内置排序函数

      sorted(iterable, key=None, reverse=False)
      
      • 1
    • iterable:可迭代对象;key:用来比较的元素,取自迭代对象中;reverse:默认False升序, True降序

      data = sorted(object.items(), key=lambda x: x[0])	# 使用x[0]的数据进行排序
      
      • 1

    5. 字典的内置函数/方法

    • 内置函数

      cmp(dict1, dict2)	# 比较两个字典元素的大小,该函数在python3中已弃用;
      # 比较原理:先比较类型如数字比字符串小、字符串类型比列表小;类型一致比较取值,数字按大小,字符按顺序等
      
      len(dict)			# 计算字典元素个数,即key的总个数
      
      type(variable)		# 返回变量类型,判断是否为dict等
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    • 内置方法

      dict.clear()			# 删除字典内所有元素
      dict.copy()				# 返回一个字典的浅复制
      dict.fromkeys(seq, val)	# 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键的初始值
      dict.get(key, default=None)	# 如前介绍,通过key获取value
      dict.items()			# 以列表返回可遍历的(键, 值)元组数组
      dict.keys()				# 以列表返回一个字典所有的键
      dict.values()			# 以列表返回字典中的所有值
      dict.update(dict2)		# 把字典dict2中的键值对更新到dict中,有:更新;没有:添加
      dict.setdefault(key, default=None)	# 与get类似。如果存在key则返回value,不存在则添加key并设置default value
      dict.pop(key, default)	# 删除key所对应的值,返回对应的value; key不给出则返回default
      dict.popitem()			# 返回并删除字典中最后一对(key, value)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

    【参考文章】
    字典的创建方式
    字典的访问1
    字典的访问2
    字典中添加元素
    字典作为函数参数1
    字典通过关键字参数传参
    字典作为可变参数时的key取值问题
    *参数和** 形参的区别

    字典cmp函数1
    字典cmp函数2
    python字典常用方法
    python字典内置函数总结

    created by shuaixio, 2023.10.05

  • 相关阅读:
    计算机毕业设计Java学生学习评价系统(源码+系统+mysql数据库+Lw文档)
    Java电子招投标采购系统源码-适合于招标代理、政府采购、企业采购、等业务的企业
    2022年HNUCM信息科学与工程学院第五届新生赛——正式赛
    sql:SQL优化知识点记录(七)
    用c语言实现静态通讯录
    矩阵分析与应用
    解读|风控模型的客观认识与深入理解
    七月论文审稿GPT第4.5版:通过15K条paper-review数据微调Llama2 70B(含各种坑)
    MySQL中符号@的作用
    最新版本Eclipse安装SVN插件Subclipse过程
  • 原文地址:https://blog.csdn.net/baidu_35692628/article/details/133578016