如何检查 Python 字典中的键是否存在且有值

PythonPythonBeginner
立即练习

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

简介

在这个实验中,你将学习如何检查 Python 字典中是否存在某个键,并验证该键对应的值不为 None。这涉及理解键值对的基本概念,以及如何使用字典来存储和检索数据。

本实验将引导你创建一个示例字典、访问其元素,然后使用 in 运算符检查键是否存在。最后,你将学习如何确保与键关联的值不是 None,从而提供一种全面的方法来验证字典数据。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559508{{"如何检查 Python 字典中的键是否存在且有值"}} python/dictionaries -.-> lab-559508{{"如何检查 Python 字典中的键是否存在且有值"}} python/data_collections -.-> lab-559508{{"如何检查 Python 字典中的键是否存在且有值"}} end

了解键值对

在这一步中,你将了解键值对,这是 Python 字典中的一个基本概念。字典用于以结构化的方式存储数据,使你能够根据关联的键快速检索值。

键值对由两部分组成:

  • 键(Key):用于访问值的唯一标识符。键必须是不可变的数据类型,如字符串、数字或元组。
  • 值(Value):与键关联的数据。值可以是任何数据类型,包括字符串、数字、列表,甚至其他字典。

让我们创建一个简单的字典来说明这个概念。

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

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

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

    ## Creating a dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Printing the dictionary
    print(my_dict)
    
    ## Accessing values using keys
    print(my_dict["name"])
    print(my_dict["age"])
    print(my_dict["city"])

    在这个例子中,我们创建了一个名为 my_dict 的字典,其中包含三对键值对:

    • "name": "Alice"
    • "age": 30
    • "city": "New York"

    然后,我们打印整个字典,并使用键来访问单个值。

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

    python ~/project/dictionary_example.py

    你应该会看到以下输出:

    {'name': 'Alice', 'age': 30, 'city': 'New York'}
    Alice
    30
    New York

    这展示了如何创建字典、以键值对的形式存储数据,以及使用相应的键访问特定的值。

字典是 Python 中组织和管理数据的强大工具。它们允许你根据唯一标识符高效地检索信息,因此对于许多编程任务来说是必不可少的。

使用 in 运算符检查键

在这一步中,你将学习如何使用 in 运算符来检查 Python 字典中是否存在某个键。当你尝试访问字典中可能不存在的键时,这是一种避免出错的实用技巧。

如果键存在于字典中,in 运算符将返回 True,否则返回 False

让我们继续使用上一步创建的字典,看看如何使用 in 运算符。

  1. 使用 VS Code 编辑器打开 ~/project 目录下的 dictionary_example.py 文件。

  2. 修改 dictionary_example.py 文件,添加以下代码:

    ## Creating a dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Checking if a key exists in the dictionary
    if "name" in my_dict:
        print("The key 'name' exists in the dictionary")
    else:
        print("The key 'name' does not exist in the dictionary")
    
    if "country" in my_dict:
        print("The key 'country' exists in the dictionary")
    else:
        print("The key 'country' does not exist in the dictionary")

    在这个示例中,我们使用 in 运算符来检查 "name""country" 这两个键是否存在于 my_dict 字典中。根据是否找到这些键,代码将打印不同的消息。

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

    python ~/project/dictionary_example.py

    你应该会看到以下输出:

    The key 'name' exists in the dictionary
    The key 'country' does not exist in the dictionary

    这展示了如何使用 in 运算符来检查字典中键的存在性。这可以帮助你编写更健壮的代码,以处理键可能缺失的情况。

通过使用 in 运算符,你可以避免在尝试访问字典中不存在的键时可能出现的 KeyError 异常。这会让你的代码更可靠,也更易于调试。

验证非 None

在这一步中,你将学习如何验证 Python 字典中与某个键关联的值是否不为 NoneNone 是 Python 中的一个特殊值,代表没有值或空值。检查是否为 None 很重要,这样可以避免在你期望某个键有有效值时出现错误。

让我们修改 dictionary_example.py 文件,添加一个值为 None 的键,然后对其进行检查。

  1. 使用 VS Code 编辑器打开 ~/project 目录下的 dictionary_example.py 文件。

  2. 修改 dictionary_example.py 文件,添加以下代码:

    ## Creating a dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York",
        "occupation": None
    }
    
    ## Checking if a key exists and its value is not None
    if "occupation" in my_dict and my_dict["occupation"] is not None:
        print("The key 'occupation' exists and its value is not None")
    else:
        print("The key 'occupation' either does not exist or its value is None")
    
    if "country" in my_dict and my_dict["country"] is not None:
        print("The key 'country' exists and its value is not None")
    else:
        print("The key 'country' either does not exist or its value is None")

    在这个示例中,我们向 my_dict 字典中添加了一个键 "occupation",其值为 None。然后,我们使用一个组合条件来检查该键是否存在,以及其值是否不为 None

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

    python ~/project/dictionary_example.py

    你应该会看到以下输出:

    The key 'occupation' either does not exist or its value is None
    The key 'country' either does not exist or its value is None

    这展示了如何同时检查键是否存在以及其值是否为 None。这是 Python 中确保处理有效数据的常见模式。

通过将 in 运算符与对 None 的检查相结合,你可以编写更健壮的代码,处理键可能缺失或其值可能未定义的情况。这有助于防止意外错误,使你的代码更可靠。

总结

在本次实验中,你学习了键值对,这是 Python 字典中的一个基本概念。你创建了一个名为 my_dict 的字典,其中包含像 "name"、"age" 和 "city" 这样的键,以及对应的 "Alice"、30 和 "New York" 等值。

然后,你使用键来访问并打印整个字典和单个值,展示了如何在 Python 中使用字典高效地存储和检索数据。本次实验强调了字典在组织和管理数据方面的重要性。