如何在 Python 中检查字典是否包含特定数量的键

PythonPythonBeginner
立即练习

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

简介

在这个实验中,你将学习如何检查 Python 字典是否包含特定数量的键。这需要使用内置的 len() 函数来探索字典的大小,以确定键值对的数量。

你将创建一个 Python 脚本,用于定义一个字典,使用 len() 函数获取其大小,并打印结果。你还将对空字典进行测试,以观察输出情况。通过这个实践,你将了解如何有效地使用 len() 函数来验证字典中的键数量。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/conditional_statements -.-> lab-559506{{"如何在 Python 中检查字典是否包含特定数量的键"}} python/dictionaries -.-> lab-559506{{"如何在 Python 中检查字典是否包含特定数量的键"}} python/build_in_functions -.-> lab-559506{{"如何在 Python 中检查字典是否包含特定数量的键"}} end

探索字典大小

在这一步中,你将学习如何确定 Python 字典的大小。字典的大小指的是它包含的键值对的数量。了解字典的大小在各种任务中都很有用,例如检查字典是否为空,或者判断它是否已达到一定的容量。

要查找字典的大小,你可以使用内置的 len() 函数。该函数会返回字典中项(键值对)的数量。

让我们通过创建一个简单的 Python 脚本来探索这一点。

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

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

    touch ~/project/dictionary_size.py
  3. 在编辑器中打开 dictionary_size.py 文件,并添加以下 Python 代码:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Get the size of the dictionary using the len() function
    dict_size = len(my_dict)
    
    ## Print the size of the dictionary
    print("The size of the dictionary is:", dict_size)

    这段代码首先创建了一个名为 my_dict 的字典,其中包含三个键值对。然后,它使用 len() 函数获取字典的大小,并将其存储在 dict_size 变量中。最后,它将字典的大小打印到控制台。

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

    python ~/project/dictionary_size.py

    你应该会看到以下输出:

    The size of the dictionary is: 3

    这个输出证实了 len() 函数能正确返回字典中键值对的数量。

  5. 让我们尝试使用一个空字典。将 dictionary_size.py 文件修改为以下内容:

    ## Create an empty dictionary
    my_dict = {}
    
    ## Get the size of the dictionary using the len() function
    dict_size = len(my_dict)
    
    ## Print the size of the dictionary
    print("The size of the dictionary is:", dict_size)
  6. 再次运行脚本:

    python ~/project/dictionary_size.py

    你应该会看到以下输出:

    The size of the dictionary is: 0

    这表明空字典的大小为 0。

对键使用 len() 函数

在上一步中,你学习了如何使用 len() 函数来确定字典中键值对的总数。在这一步,你将探索如何结合使用 len() 函数和 .keys() 方法来查找字典中键的数量。

.keys() 方法返回一个视图对象,该对象展示了字典中所有键的列表。然后,你可以对这个视图对象使用 len() 函数来获取键的数量。当你只需要知道键的数量,而不需要知道键值对的总数时,这种方法很有用。

让我们修改上一步的 Python 脚本来演示这一点。

  1. 在 VS Code 编辑器中打开 dictionary_size.py 文件(如果它还没有打开的话)。

  2. dictionary_size.py 文件修改为以下 Python 代码:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Get the keys of the dictionary using the .keys() method
    keys = my_dict.keys()
    
    ## Get the number of keys using the len() function
    num_keys = len(keys)
    
    ## Print the number of keys
    print("The number of keys in the dictionary is:", num_keys)

    在这段代码中,我们首先创建了一个名为 my_dict 的字典。然后,我们使用 .keys() 方法获取包含字典中所有键的视图对象,并将这个视图对象存储在 keys 变量中。最后,我们使用 len() 函数获取 keys 视图对象中键的数量,并打印结果。

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

    python ~/project/dictionary_size.py

    你应该会看到以下输出:

    The number of keys in the dictionary is: 3

    这个输出证实了 len() 函数与 .keys() 方法结合使用时,能正确返回字典中键的数量。

  4. 现在,让我们尝试向字典中添加一个新的键值对,看看这会如何影响键的数量。将 dictionary_size.py 文件修改为以下内容:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Add a new key-value pair
    my_dict["occupation"] = "Engineer"
    
    ## Get the keys of the dictionary using the .keys() method
    keys = my_dict.keys()
    
    ## Get the number of keys using the len() function
    num_keys = len(keys)
    
    ## Print the number of keys
    print("The number of keys in the dictionary is:", num_keys)
  5. 再次运行脚本:

    python ~/project/dictionary_size.py

    你应该会看到以下输出:

    The number of keys in the dictionary is: 4

    这表明添加一个新的键值对会增加字典中键的数量。

与期望数量进行比较

在前面的步骤中,你学习了如何确定字典的大小以及如何统计键的数量。在这一步,你将学习如何将字典的大小(或键的数量)与期望的数量进行比较。当你需要在进行进一步操作之前验证字典是否具有特定数量的键值对或键时,这非常有用。

让我们修改上一步的 Python 脚本来演示这一点。

  1. 在 VS Code 编辑器中打开 dictionary_size.py 文件(如果它还没有打开的话)。

  2. dictionary_size.py 文件修改为以下 Python 代码:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Desired count
    desired_count = 3
    
    ## Get the size of the dictionary
    dict_size = len(my_dict)
    
    ## Compare with desired count
    if dict_size == desired_count:
        print("The dictionary size matches the desired count.")
    else:
        print("The dictionary size does not match the desired count.")
    
    ## Get the number of keys
    num_keys = len(my_dict.keys())
    
    ## Compare the number of keys with desired count
    if num_keys == desired_count:
        print("The number of keys matches the desired count.")
    else:
        print("The number of keys does not match the desired count.")

    在这段代码中,我们首先创建了一个名为 my_dict 的字典,并将 desired_count 变量设置为 3。然后,我们使用 len() 函数获取字典的大小,并将其与 desired_count 进行比较。我们打印一条消息,指示字典的大小是否与期望的数量匹配。接着,我们对字典中键的数量重复相同的过程。

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

    python ~/project/dictionary_size.py

    你应该会看到以下输出:

    The dictionary size matches the desired count.
    The number of keys matches the desired count.

    这个输出证实了字典的大小和键的数量都与期望的数量 3 相匹配。

  4. 现在,让我们修改字典和期望的数量,看看比较结果会如何变化。将 dictionary_size.py 文件修改为以下内容:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Add a new key-value pair
    my_dict["occupation"] = "Engineer"
    
    ## Desired count
    desired_count = 4
    
    ## Get the size of the dictionary
    dict_size = len(my_dict)
    
    ## Compare with desired count
    if dict_size == desired_count:
        print("The dictionary size matches the desired count.")
    else:
        print("The dictionary size does not match the desired count.")
    
    ## Get the number of keys
    num_keys = len(my_dict.keys())
    
    ## Compare the number of keys with desired count
    if num_keys == desired_count:
        print("The number of keys matches the desired count.")
    else:
        print("The number of keys does not match the desired count.")
  5. 再次运行脚本:

    python ~/project/dictionary_size.py

    你应该会看到以下输出:

    The dictionary size matches the desired count.
    The number of keys matches the desired count.

    现在,字典的大小和键的数量都与更新后的期望数量 4 相匹配。

总结

在这个实验中,你学习了如何使用 len() 函数来确定 Python 字典的大小。本实验涉及创建一个 Python 脚本 dictionary_size.py 来探索这一功能。你创建了一个包含键值对的示例字典,然后使用 len(my_dict) 来获取字典中的项数,并将结果打印到控制台。

本实验还展示了 len() 函数在空字典上的工作方式,强调了它即使在字典为空时也能准确返回键值对数量的能力。这一知识对于检查字典是否为空或确定字典是否已达到特定容量等任务至关重要。