如何在 Python 中检查字典是否为空

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习如何在 Python 中判断一个字典是否为空。本实验涵盖了使用花括号 {}dict() 构造函数创建空字典的方法。然后,你将探索如何使用 len() 函数来检查字典中键值对的数量,从而有效地识别空字典。

最后,本实验将展示在布尔上下文环境中如何对空字典进行求值,让你全面了解在 Python 中处理和识别空字典的方法。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ObjectOrientedProgrammingGroup(["Object-Oriented Programming"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ObjectOrientedProgrammingGroup -.-> python/constructor("Constructor") subgraph Lab Skills python/booleans -.-> lab-559507{{"如何在 Python 中检查字典是否为空"}} python/dictionaries -.-> lab-559507{{"如何在 Python 中检查字典是否为空"}} python/build_in_functions -.-> lab-559507{{"如何在 Python 中检查字典是否为空"}} python/constructor -.-> lab-559507{{"如何在 Python 中检查字典是否为空"}} end

了解空字典

在这一步中,你将了解 Python 中的空字典。字典是键值对的集合,而空字典就是不包含任何键值对的字典。掌握如何创建和使用空字典是许多编程任务的基础。

要创建一个空字典,你可以使用花括号 {}dict() 构造函数。让我们通过实际操作来看看如何实现。

  1. 在 LabEx 环境中打开 VS Code 编辑器。

  2. ~/project 目录下创建一个名为 empty_dict.py 的新文件。

    ~/project/empty_dict.py
  3. empty_dict.py 文件中添加以下 Python 代码:

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)

    这段代码使用不同的方法创建了两个空字典 empty_dict_1empty_dict_2。然后使用 print() 函数来显示这些字典。

  4. 在终端中使用以下命令运行 Python 脚本:

    python ~/project/empty_dict.py

    你应该会看到以下输出:

    Empty dictionary 1: {}
    Empty dictionary 2: {}

    这个输出证实了这两种方法都成功创建了空字典。

空字典是构建更复杂数据结构的有用起点。你可以根据需要向其中添加键值对。在接下来的步骤中,你将学习如何检查字典是否为空,以及空字典在布尔上下文环境中是如何求值的。

使用 len() 进行检查

在这一步中,你将学习如何使用 len() 函数来检查字典是否为空。len() 函数会返回字典中元素(键值对)的数量。如果字典为空,len() 函数将返回 0。

让我们修改上一步创建的 empty_dict.py 文件,加入 len() 函数。

  1. 在 VS Code 编辑器中打开 empty_dict.py 文件。

    ~/project/empty_dict.py
  2. 修改 empty_dict.py 文件中的 Python 代码,加入 len() 函数:

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    print("Length of empty_dict_1:", len(empty_dict_1))
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)
    print("Length of empty_dict_2:", len(empty_dict_2))
    
    ## Checking if a dictionary is empty using len()
    if len(empty_dict_1) == 0:
        print("empty_dict_1 is empty")
    else:
        print("empty_dict_1 is not empty")

    这段代码使用 len() 函数计算空字典的长度并打印结果。它还展示了如何在条件语句中使用 len() 函数来检查字典是否为空。

  3. 在终端中使用以下命令运行 Python 脚本:

    python ~/project/empty_dict.py

    你应该会看到以下输出:

    Empty dictionary 1: {}
    Length of empty_dict_1: 0
    Empty dictionary 2: {}
    Length of empty_dict_2: 0
    empty_dict_1 is empty

    这个输出证实了 len() 函数对于空字典会返回 0,并且条件语句能正确判断字典为空。

使用 len() 函数是判断字典是否包含任何键值对的简单有效方法。在各种场景中这都很有用,例如当你需要根据字典是否为空来执行不同的操作时。

作为布尔值进行求值

在这一步中,你将学习空字典在布尔上下文环境中是如何求值的。在 Python 里,当某些值用于布尔上下文(例如 if 语句)时,会被视为“真值”(求值为 True),而其他值则被视为“假值”(求值为 False)。空字典被视为“假值”。

让我们修改你一直在编辑的 empty_dict.py 文件,来演示这个概念。

  1. 在 VS Code 编辑器中打开 empty_dict.py 文件。

    ~/project/empty_dict.py
  2. 修改 empty_dict.py 文件中的 Python 代码,加入对空字典的布尔求值:

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    print("Length of empty_dict_1:", len(empty_dict_1))
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)
    print("Length of empty_dict_2:", len(empty_dict_2))
    
    ## Checking if a dictionary is empty using len()
    if len(empty_dict_1) == 0:
        print("empty_dict_1 is empty")
    else:
        print("empty_dict_1 is not empty")
    
    ## Evaluating an empty dictionary as a boolean
    if empty_dict_1:
        print("empty_dict_1 is truthy")
    else:
        print("empty_dict_1 is falsy")

    这段代码添加了一个 if 语句,直接对 empty_dict_1 变量进行求值。由于它是一个空字典,在布尔上下文环境中会被视为 False

  3. 在终端中使用以下命令运行 Python 脚本:

    python ~/project/empty_dict.py

    你应该会看到以下输出:

    Empty dictionary 1: {}
    Length of empty_dict_1: 0
    Empty dictionary 2: {}
    Length of empty_dict_2: 0
    empty_dict_1 is empty
    empty_dict_1 is falsy

    这个输出证实了空字典 empty_dict_1if 语句中被求值为“假值”。

了解空字典求值为 False 可以简化你的代码,使其更具可读性。你可以直接在布尔上下文环境中使用字典,而无需显式检查其长度。

总结

在这个实验中,你学习了 Python 中的空字典,以及如何使用花括号 {}dict() 构造函数来创建它们。你创建了一个 empty_dict.py 文件,并使用 print() 函数显示所创建的空字典,从而确认这两种方法都能成功创建空字典。

本实验还介绍了使用 len() 函数检查字典是否为空的概念,后续步骤将对此进行更深入的探讨。