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

PythonPythonBeginner
立即练习

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

简介

在这个实验中,你将学习如何在 Python 中检查一个变量是否为字典。字典是用于存储键值对数据的基本数据结构。你将从理解字典的基础知识开始,包括如何使用花括号 {} 和基于键的索引来创建、访问和修改字典。

然后,本实验将指导你使用 type() 函数和 isinstance() 函数来识别一个变量是否为字典。你将创建 Python 脚本以测试这些方法并观察输出,从而巩固你对如何通过编程方式确定一个变量是否包含字典对象的理解。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-559599{{"如何在 Python 中检查变量是否为字典"}} python/booleans -.-> lab-559599{{"如何在 Python 中检查变量是否为字典"}} python/dictionaries -.-> lab-559599{{"如何在 Python 中检查变量是否为字典"}} python/build_in_functions -.-> lab-559599{{"如何在 Python 中检查变量是否为字典"}} python/data_collections -.-> lab-559599{{"如何在 Python 中检查变量是否为字典"}} end

理解字典

在这一步中,你将学习字典,它是 Python 中的一种基本数据结构。字典用于以键值对的形式存储数据,使你能够根据关联的键快速检索值。

字典使用花括号 {} 来定义。每个键值对用冒号 : 分隔,键值对之间用逗号 , 分隔。以下是一个简单的示例:

my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict)

为了使用字典,让我们使用 VS Code 编辑器在你的 ~/project 目录中创建一个名为 dictionary_example.py 的 Python 文件。

打开 VS Code,在 ~/project 目录中创建一个名为 dictionary_example.py 的新文件,并添加以下内容:

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

## Print the entire dictionary
print(my_dict)

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

python ~/project/dictionary_example.py

你应该会看到以下输出:

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

要访问字典中的特定值,请使用方括号 [] 内的键:

name = my_dict["name"]
print(name)

修改你的 dictionary_example.py 文件,使其包含以下行:

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

## Access a value using the key
name = my_dict["name"]
print(name)

再次执行脚本:

python ~/project/dictionary_example.py

现在的输出将是:

Alice

你还可以向字典中添加新的键值对:

my_dict["occupation"] = "Engineer"
print(my_dict)

更新你的 dictionary_example.py 文件:

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

## Add a new key-value pair
my_dict["occupation"] = "Engineer"
print(my_dict)

运行脚本:

python ~/project/dictionary_example.py

输出将是:

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

字典是可变的,这意味着你可以更改与键关联的值:

my_dict["age"] = 31
print(my_dict)

修改你的 dictionary_example.py 文件:

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

## Change the value of an existing key
my_dict["age"] = 31
print(my_dict)

执行脚本:

python ~/project/dictionary_example.py

输出将是:

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

理解字典对于在 Python 中处理结构化数据至关重要。它们提供了一种灵活且高效的方式来存储和检索信息。

使用 type() 进行识别

在这一步中,你将学习如何使用 Python 中的 type() 函数来识别变量的数据类型。这是一个了解你所处理的数据类型以及调试代码的有用工具。

type() 函数返回对象的类型。例如,如果你有一个包含整数的变量,type() 将返回 <class 'int'>。如果它包含字符串,则返回 <class 'str'>,依此类推。

让我们继续使用你在上一步中创建的 dictionary_example.py 文件。我们将添加一些代码来识别不同变量的类型。

在 VS Code 中打开 dictionary_example.py 并添加以下行:

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

## Check the type of the dictionary
print(type(my_dict))

## Access a value
name = my_dict["name"]

## Check the type of the value
print(type(name))

## Check the type of the age
age = my_dict["age"]
print(type(age))

现在,使用以下命令执行 Python 脚本:

python ~/project/dictionary_example.py

你应该会看到以下输出:

<class 'dict'>
<class 'str'>
<class 'int'>

这个输出告诉你,my_dict 是一个字典 (dict),name 是一个字符串 (str),age 是一个整数 (int)。

你还可以将 type() 用于其他数据类型,如列表和布尔值。让我们在 dictionary_example.py 中添加更多示例:

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

## Check the type of the dictionary
print(type(my_dict))

## Access a value
name = my_dict["name"]

## Check the type of the value
print(type(name))

## Check the type of the age
age = my_dict["age"]
print(type(age))

## Create a list
my_list = [1, 2, 3]
print(type(my_list))

## Create a boolean
is_adult = True
print(type(is_adult))

再次执行脚本:

python ~/project/dictionary_example.py

现在的输出将是:

<class 'dict'>
<class 'str'>
<class 'int'>
<class 'list'>
<class 'bool'>

如你所见,type() 是一个通用的函数,它可以帮助你了解在 Python 中所处理的数据类型。当你处理复杂的数据结构或不确定变量的类型时,这尤其有用。

使用 isinstance() 进行确认

在这一步中,你将学习如何使用 Python 中的 isinstance() 函数来确认一个对象是否是某个特定类或类型的实例。这个函数比 type() 更强大,因为它还会考虑继承关系。

isinstance() 函数接受两个参数:你要检查的对象,以及你要与之进行比较的类或类型。如果对象是指定类或类型的实例,它将返回 True,否则返回 False

让我们继续使用 dictionary_example.py 文件。我们将添加一些代码,使用 isinstance() 来确认不同变量的类型。

在 VS Code 中打开 dictionary_example.py 并添加以下行:

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

## Check if my_dict is a dictionary
print(isinstance(my_dict, dict))

## Access a value
name = my_dict["name"]

## Check if name is a string
print(isinstance(name, str))

## Check if age is an integer
age = my_dict["age"]
print(isinstance(age, int))

现在,使用以下命令执行 Python 脚本:

python ~/project/dictionary_example.py

你应该会看到以下输出:

True
True
True

这个输出确认了 my_dict 是一个字典,name 是一个字符串,age 是一个整数。

你还可以通过将一个类型元组作为第二个参数传递给 isinstance(),来一次性检查对象是否属于多个类型中的任意一个。例如:

## Check if age is either an integer or a float
print(isinstance(age, (int, float)))

修改你的 dictionary_example.py 文件,加入这个检查:

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

## Check if my_dict is a dictionary
print(isinstance(my_dict, dict))

## Access a value
name = my_dict["name"]

## Check if name is a string
print(isinstance(name, str))

## Check if age is an integer
age = my_dict["age"]
print(isinstance(age, int))

## Check if age is either an integer or a float
print(isinstance(age, (int, float)))

再次执行脚本:

python ~/project/dictionary_example.py

现在的输出将是:

True
True
True
True

isinstance() 是 Python 中进行类型检查的强大工具,特别是在处理继承关系或需要检查对象是否属于多个类型中的任意一个时。通过确保你的变量是预期的类型,它能帮助你编写更健壮、可靠的代码。

总结

在这个实验中,你学习了 Python 中的字典,它是一种以键值对形式存储数据的基础数据结构。你创建了一个字典,使用键来访问值,并添加了新的键值对。

你还练习了使用 type() 函数和 isinstance() 函数来验证一个变量是否为字典。type() 函数返回对象的类型,而 isinstance() 则检查对象是否为指定类或类型的实例。