Python基础语法第六章之字典

简介: 啥是键值对?这是计算机/生活中一个非常广泛使用的概念.把 键(key) 和 值(value) 进行一个一对一的映射, 然后就可以根据键, 快速找到值.

 一、字典

1.1字典是什么

字典是一种存储 键值对 的结构.

啥是键值对? 这是计算机/生活中一个非常广泛使用的概念.

把 键(key) 和 值(value) 进行一个一对一的映射, 然后就可以根据键, 快速找到值.

1.2创建字典

    • 创建一个空的字典. 使用 { } 表示字典.
    a = { }
    b = dict()
    print(type(a))
    print(type(b))

    image.gif

    也可以在创建的同时指定初始值

    键值对之间使用 , 分割, 键和值之间使用 : 分割. (冒号后面推荐加一个空格).

    使用 print 来打印字典内容

    student = { 'id': 1, 'name': 'zhangsan' }
    print(student)

    image.gif

    image.gif编辑

      • 为了代码更规范美观, 在创建字典的时候往往会把多个键值对, 分成多行来书写.
      student = {
          'id': 1,
          'name': 'zhangsan'
      }

      image.gif

      最后一个键值对, 后面可以写 , 也可以不写.

      1.3查找 key

        • 使用 in 可以判定 key 是否在 字典 中存在. 返回布尔值.
        student = {
            'id': 1,
            'name': 'zhangsan',
        }
        print('id' in student)
        print('score' in student)

        image.gif

        image.gif编辑

          • 使用 [ ] 通过类似于取下标的方式, 获取到元素的值. 只不过此处的 "下标" 是 key. (可能是整数, 也可能是字符串等其他类型).
          student = {
              'id': 1,
              'name': 'zhangsan',
          }
          print(student['id'])
          print(student['name'])

          image.gif

          image.gif编辑

            • 如果 key 在字典中不存在, 则会抛出异常.
            student = {
                'id': 1,
                'name': 'zhangsan',
            }
            print(student['score'])

            image.gif

            image.gif编辑

            1.4新增/修改元素

            使用 [ ] 可以根据 key 来新增/修改 value.

              • 如果 key 不存在, 对取下标操作赋值, 即为新增键值对
              student = {
                  'id': 1,
                  'name': 'zhangsan',
              }
              student['score'] = 90
              print(student)

              image.gif

              image.gif编辑

                • 如果 key 已经存在, 对取下标操作赋值, 即为修改键值对的值.
                student = {
                    'id': 1,
                    'name': 'zhangsan',
                    'score': 80
                }
                student['score'] = 90
                print(student)

                image.gif

                image.gif编辑

                1.5删除元素

                  • 使用 pop 方法根据 key 删除对应的键值对.
                  student = {
                      'id': 1,
                      'name': 'zhangsan',
                      'score': 80
                  }
                  student.pop('score')
                  print(student)

                  image.gif

                  image.gif编辑

                  1.6遍历字典元素

                  直接使用 for 循环能够获取到字典中的所有的 key, 进一步的就可以取出每个值了.

                  student = {
                      'id': 1,
                      'name': 'zhangsan',
                      'score': 80
                  }
                  for key in student:
                      print(key, student[key])

                  image.gif

                  image.gif编辑

                  1.7取出所有 key 和 value

                    • 使用 keys 方法可以获取到字典中的所有的 key
                    student = {
                        'id': 1,
                        'name': 'zhangsan',
                        'score': 80
                    }
                    print(student.keys())

                    image.gif

                    image.gif编辑

                    此处 dict_keys 是一个特殊的类型, 专门用来表示字典的所有 key. 大部分元组支持的操作对于

                    dict_keys 同样适用.

                      • 使用 values 方法可以获取到字典中的所有 value
                      student = {
                          'id': 1,
                          'name': 'zhangsan',
                          'score': 80
                      }
                      print(student.values())

                      image.gif

                      image.gif编辑

                        • 使用 items 方法可以获取到字典中所有的键值对
                        student = {
                            'id': 1,
                            'name': 'zhangsan',
                            'score': 80
                        }
                        print(student.items())

                        image.gif

                        image.gif编辑

                        1.8合法的 key 类型

                        字典本质上是一个 哈希表, 哈希表的 key 要求是 "可哈希的", 也就是可以计算出一个哈希值.

                          • 可以使用 hash 函数计算某个对象的哈希值.
                          • 但凡能够计算出哈希值的类型, 都可以作为字典的 key.
                          print(hash(0))
                          print(hash(3.14))
                          print(hash('hello'))
                          print(hash(True))
                          print(hash(())) # ( ) 是一个空的元组

                          image.gif

                          image.gif编辑

                            • 列表无法计算哈希值.
                            print(hash([1, 2, 3]))

                            image.gif

                            image.gif编辑

                              • 字典也无法计算哈希值
                              print(hash({ 'id': 1 }))

                              image.gif

                              image.gif编辑

                              目录
                              相关文章
                              |
                              6天前
                              |
                              存储 索引 Python
                              Python学习笔记----列表、元组和字典的基础操作
                              这篇文章是一份Python学习笔记,涵盖了列表、元组和字典的基础操作,包括它们的创建、修改、删除、内置函数和方法等。
                              Python学习笔记----列表、元组和字典的基础操作
                              |
                              12天前
                              |
                              存储 数据挖掘 程序员
                              揭秘Python:掌握这些基本语法和数据类型,你将拥有编程世界的钥匙!
                              【8月更文挑战第8天】Python是一种高级、解释型语言,以简洁的语法和强大的功能广受好评。本文从基本语法入手,强调Python独特的缩进规则,展示清晰的代码结构。接着介绍了Python的主要数据类型,包括数值、字符串、列表、元组、集合和字典,并提供了示例代码。通过这些基础知识的学习,你将为深入探索Python及其在文本处理、数据分析等领域的应用打下坚实的基础。
                              26 3
                              |
                              13天前
                              |
                              存储 索引 Python
                              探究 Python3 字典的现世
                              【8月更文挑战第6天】Python 3 中的字典是一种内置数据类型,采用键值对形式存储数据,支持通过键快速检索值。字典无序且可变,键唯一。创建字典可用 `{}` 或 `dict()` 函数,访问、更新和删除条目分别通过索引、`update()` 和 `del` 实现。
                              25 1
                              |
                              21天前
                              |
                              存储 Python
                              Python 基础语法变量
                              【7月更文挑战第27天】
                              31 9
                              |
                              21天前
                              |
                              开发者 Python
                              Python 基础语法注释
                              【7月更文挑战第27天】
                              24 6
                              |
                              17天前
                              |
                              JSON 数据格式 Python
                              【python】解决json.dump(字典)时报错Object of type ‘float32‘ is not JSON serializable
                              在使用json.dump时遇到的“Object of type ‘float32’ is not JSON serializable”错误的方法,通过自定义一个JSON编码器类来处理NumPy类型的数据。
                              18 1
                              |
                              18天前
                              |
                              Python
                              【Python】对字典进行排序
                              该文档介绍了如何在Python中对字典进行排序的方法。
                              12 2
                              |
                              4天前
                              |
                              存储 数据安全/隐私保护 索引
                              Python基础语法day02字符串详解和列表
                              Python基础语法day02字符串详解和列表
                              |
                              4天前
                              |
                              Python
                              Python基础语法day01基础语句
                              Python基础语法day01基础语句
                              |
                              6天前
                              |
                              SQL 分布式计算 算法
                              【python】python指南(十四):**操作符解包字典传参
                              【python】python指南(十四):**操作符解包字典传参
                              14 0