• 技术文章 >Python技术 >Python基础教程

    python ChainMap如何实现字典操作

    小妮浅浅小妮浅浅2021-09-02 09:25:40原创2745

    1、ChainMap支持与常规字典相同的API访问现有密钥。可以用字典样式的键来搜索现有的键,或者可以用.get()。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    >>> from collections import ChainMap

      

    >>> numbers = {"one": 1, "two": 2}

    >>> letters = {"a": "A", "b": "B"}

      

    >>> alpha_num = ChainMap(numbers, letters)

    >>> alpha_num["two"]

    2

      

    >>> alpha_num.get("a")

    'A'

      

    >>> alpha_num["three"]

    Traceback (most recent call last):

        ...

    KeyError: 'three'

    2、在搜索目标链映射中搜索所有映射,直到找到所需的键。

    如果密钥不存在,您将获得通常的KeyError。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    >>> from collections import ChainMap

      

    >>> for_adoption = {"dogs": 10, "cats": 7, "pythons": 3}

    >>> vet_treatment = {"dogs": 4, "cats": 3, "turtles": 1}

    >>> pets = ChainMap(for_adoption, vet_treatment)

      

    >>> pets["dogs"]

    10

    >>> pets.get("cats")

    7

    >>> pets["turtles"]

    1

    以上就是python ChainMap实现字典操作的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python chainmap
    上一篇:python中ChainMap如何创建对象 下一篇:python update合并字典的方法

    相关文章推荐

    • Python制作七夕比心表白• python os.chdir()的使用• python OpenCV加法操作的实现• python OpenCV中的光学字符识别介绍• python OpenCV的图像处理• python中Qt是什么• python浏览器操作有哪些• python等待方式的介绍• 常用6种顶级Python文本编辑器• python中ChainMap是什么• python中ChainMap如何实例化• python中ChainMap如何创建对象

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网