如何在 Python 中检查字典是否包含特定值

PythonPythonBeginner
立即练习

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

简介

在这个实验中,你将学习如何检查 Python 字典中是否包含特定的值。实验首先会介绍字典的值,并演示如何使用键和 .values() 方法来访问它们。你将在 ~/project 目录下创建一个 dictionary_example.py 文件,并执行 Python 代码来打印字典的值,既可以逐个打印,也可以作为一个集合打印。

接着,实验会指导你在 values() 视图对象上使用 in 运算符,以高效地确定字典中是否存在特定的值。最后,实验会探索使用迭代来查找匹配项的另一种方法,让你全面了解在 Python 字典中检查值的不同方法。


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/ControlFlowGroup -.-> python/for_loops("For Loops") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559504{{"如何在 Python 中检查字典是否包含特定值"}} python/for_loops -.-> lab-559504{{"如何在 Python 中检查字典是否包含特定值"}} python/dictionaries -.-> lab-559504{{"如何在 Python 中检查字典是否包含特定值"}} python/data_collections -.-> lab-559504{{"如何在 Python 中检查字典是否包含特定值"}} end

理解字典的值

在这一步中,你将学习 Python 字典的值。字典是一种基本的数据结构,它以键值对的形式存储数据。了解如何访问和操作这些值对于有效地使用字典至关重要。

首先,让我们创建一个简单的字典:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Print the dictionary
print(my_dict)

使用 VS Code 编辑器在你的 ~/project 目录下创建一个名为 dictionary_example.py 的文件。将上述代码复制并粘贴到该文件中。

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

python dictionary_example.py

你应该会看到以下输出:

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

要访问字典中的值,你可以使用键。例如,要访问与键 "name" 关联的值,你可以使用 my_dict["name"]

让我们修改 dictionary_example.py 文件以访问并打印这些值:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Access and print the values
print(my_dict["name"])
print(my_dict["age"])
print(my_dict["city"])

保存对 dictionary_example.py 文件的更改并再次运行它:

python dictionary_example.py

现在的输出应该是:

Alice
30
New York

你还可以使用 .values() 方法来获取字典中所有值的集合。此方法返回一个视图对象,该对象显示字典中所有值的列表。

修改 dictionary_example.py 文件以使用 .values() 方法:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Get the values
values = my_dict.values()

## Print the values
print(values)

保存对 dictionary_example.py 文件的更改并再次运行它:

python dictionary_example.py

现在的输出应该是:

dict_values(['Alice', 30, 'New York'])

如你所见,.values() 方法返回一个包含字典中所有值的视图对象。你可以遍历这个视图对象来逐个访问每个值,这将在接下来的步骤中学习。

values() 上使用 in 运算符

在这一步中,你将学习如何使用 in 运算符来检查字典的值中是否存在特定的值。in 运算符是 Python 中用于搜索和验证数据的强大工具。

从上一步继续,让我们使用相同的字典 my_dict。我们将检查值 "Alice" 是否存在于字典的值中。

修改你 ~/project 目录下的 dictionary_example.py 文件,加入以下代码:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Check if "Alice" is in the values
if "Alice" in my_dict.values():
    print("Alice is in the dictionary values")
else:
    print("Alice is not in the dictionary values")

保存对 dictionary_example.py 文件的更改并再次运行它:

python dictionary_example.py

输出应该是:

Alice is in the dictionary values

现在,让我们检查一个字典中不存在的值,例如 "Bob"

修改 dictionary_example.py 文件,检查 "Bob" 而不是 "Alice"

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Check if "Bob" is in the values
if "Bob" in my_dict.values():
    print("Bob is in the dictionary values")
else:
    print("Bob is not in the dictionary values")

保存对 dictionary_example.py 文件的更改并再次运行它:

python dictionary_example.py

现在的输出应该是:

Bob is not in the dictionary values

in 运算符区分大小写。让我们检查 "alice"(小写)是否在字典的值中:

修改 dictionary_example.py 文件以检查 "alice"

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Check if "alice" is in the values
if "alice" in my_dict.values():
    print("alice is in the dictionary values")
else:
    print("alice is not in the dictionary values")

保存对 dictionary_example.py 文件的更改并再次运行它:

python dictionary_example.py

现在的输出应该是:

alice is not in the dictionary values

这表明 in 运算符区分大小写,只有找到完全匹配的值时才会返回 True

迭代查找匹配项

在这一步中,你将学习如何遍历字典的值,并根据特定条件查找匹配项。当你需要处理或过滤存储在字典中的数据时,这是一项常见的任务。

从上一步继续,让我们使用相同的字典 my_dict。我们将遍历这些值,并仅打印那些为字符串的值。

修改你 ~/project 目录下的 dictionary_example.py 文件,加入以下代码:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Iterate through the values
for value in my_dict.values():
    ## Check if the value is a string
    if isinstance(value, str):
        print(value)

保存对 dictionary_example.py 文件的更改并再次运行它:

python dictionary_example.py

输出应该是:

Alice
New York

在这个示例中,我们使用 for 循环遍历字典值中的每个值。在循环内部,我们使用 isinstance() 函数检查该值是否为字符串。如果是,我们就打印该值。

现在,让我们修改代码以查找大于 25 的值。由于年龄是一个整数,我们可以检查它是否大于 25。

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

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Iterate through the values
for value in my_dict.values():
    ## Check if the value is an integer and greater than 25
    if isinstance(value, int) and value > 25:
        print(value)

保存对 dictionary_example.py 文件的更改并再次运行它:

python dictionary_example.py

现在的输出应该是:

30

这展示了你如何将迭代与条件语句结合起来,在字典的值中查找特定的匹配项。你可以根据自己的需求,将这种方法应用于不同的数据类型和条件。

总结

在这个实验中,你学习了 Python 中的字典值。字典是一种基本的数据结构,它以键值对的形式存储数据。你创建了一个字典,并使用键来访问其值,打印出了与“name”、“age”和“city”相关联的值。

此外,你还探索了 .values() 方法,该方法会返回一个包含字典所有值的视图对象。你修改了脚本以使用此方法,并打印出了值的集合。