当前位置: 首页 > news >正文

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

文章目录

      • 序言
      • 1. 字典的创建和访问
      • 2. 字典如何添加元素
      • 3. 字典作为函数参数
      • 4. 字典排序

序言

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

1. 字典的创建和访问

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

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

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

  • 字典的创建

    • 创建空字典

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

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

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

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

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

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

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

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

  • 字典的访问

    • 通过键值对访问

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

      dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}
      print(dictionary.get(3, '字典中不存在键为3的元素'))
      
    • 遍历字典的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)
      
    • 遍历字典的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)
      
    • 遍历嵌套字典

      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)
      

2. 字典如何添加元素

  • 使用[]

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

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

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'] = 24dict_fix(dictionary)print(dictionary)	# age : 24
    
  • 字典作为可变参数时:函数内对字典修改,不会影响到原来的字典

    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 : 22arg['age'] = 24dict_fix(**dictionary)print('\n', dictionary)	# age : 22
    
  • 关于字典作为**可变参数时的key类型说明

    dictionary = {}
    dictionary.update({2: 'test'})
    print(dictionary, '\n')def dict_fix(**arg):for key, value in arg.items():print(key, '->', value)arg['age'] = 24dict_fix(**dictionary)
    
    • 报错: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)
    
  • 补充一个例子

    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}
    
    • 对于不使用关键字传递的变量,会被作为元组的一部分传递给*a,而使用关键字传递的变量作为字典的一部分传递给了**b

4. 字典排序

  • 使用python内置排序函数

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

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

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

created by shuaixio, 2023.10.05

http://www.lryc.cn/news/182721.html

相关文章:

  • 基于Java的大学生心理咨询系统设计与实现(源码+lw+部署文档+讲解等)
  • Redis-双写一致性
  • CustomTkinter:创建现代、可定制的Python UI
  • 华为OD机试真题【不含 101 的数】
  • Spring IoC和DI详解
  • mysql-binlog
  • 通过BeanFactotyPostProcessor动态修改@FeignClient的path
  • 数据结构与算法系列-二分查找
  • CSS 毛玻璃特效运用目录
  • 如何在Qt6中引入Network模块
  • 2023/10/4 QT实现TCP服务器客户端搭建
  • 云原生边缘计算KubeEdge安装配置
  • 【LeetCode热题100】--35.搜索插入位置
  • mysql面试题13:MySQL中什么是异步复制?底层实现?
  • SpringBoot-Shiro安全权限框架
  • PostgreSQL基础语法
  • 编程前置:处理Excel表格,定位单元格位置,输入文字前,让AI机器人知道我说什么
  • Linux基本指令介绍系列第四篇
  • 读取vivo手机截图尺寸移动.jpg等文件
  • Web前端-Vue2+Vue3基础入门到实战项目-Day2(指令补充, computed计算属性, watch侦听器, 水果购物车)
  • ffmpeg之去除视频水印
  • 第二章 线性表
  • Java 超高频常见字符操作【建议收藏】
  • MongoDB数据库网站网页实例-编程语言Python+Django
  • 开箱报告,Simulink Toolbox库模块使用指南(七)——S-Fuction Builter模块
  • spring-boot 操作 mongodb 数据库
  • JVM篇---第三篇
  • 建筑施工行业招投标资源众包分包系统站点开发
  • 【Linux基础】Linux发展史
  • openGauss学习笔记-90 openGauss 数据库管理-内存优化表MOT管理-内存表特性-使用MOT-MOT使用重试中止事务