嵌套字典
Python 中的嵌套字典是指作为值存储在另一个字典中的字典。换句话说,字典可以包含其他字典作为其值,从而形成分层或嵌套结构。
嵌套字典可以像常规字典一样进行修改、更新或扩展。您可以在嵌套结构的任何级别添加、删除或更新键值对。
在 Python 中创建嵌套字典
我们可以通过定义一个字典在 Python 中创建一个嵌套字典,其中某些键的值本身就是字典。这允许创建层次结构,其中每个键值对代表一个级别的嵌套信息。这可以通过多种方式实现 -
示例:直接分配
在这种方法中,我们可以直接将字典作为值分配给单个字典定义中的外部键 -
# Define the outer dictionary
nested_dict = {
"outer_key1": {"inner_key1": "value1", "inner_key2": "value2"},
"outer_key2": {"inner_key3": "value3", "inner_key4": "value4"}
}
print(nested_dict)
示例:使用 Loop
使用此方法,初始化一个空的外部字典,然后使用循环定义嵌套字典来填充字典作为值 -
# Define an empty outer dictionary
nested_dict = {}
# Add key-value pairs to the outer dictionary
outer_keys = ["outer_key1", "outer_key2"]
for key in outer_keys:
nested_dict[key] = {"inner_key1": "value1", "inner_key2": "value2"}
print(nested_dict)
在 Python 中向嵌套字典添加项
创建嵌套字典后,我们可以通过使用其键访问特定的嵌套字典,然后为其分配新的键值对来向其添加项目。
例在以下示例中,我们将定义一个嵌套字典 “students”,其中每个键表示学生的姓名,其值是另一个包含学生详细信息的字典。
然后,我们将一个新的键值对添加到 Alice 的嵌套字典中,并为新学生 Charlie -
# Initial nested dictionary
students = {
"Alice": {"age": 21, "major": "Computer Science"},
"Bob": {"age": 20, "major": "Engineering"}
}
# Adding a new key-value pair to Alice's nested dictionary
students["Alice"]["GPA"] = 3.8
# Adding a new nested dictionary for a new student
students["Charlie"] = {"age": 22, "major": "Mathematics"}
print(students)
它将产生以下输出 -
在 Python 中访问嵌套字典的项
在 Python 中访问嵌套字典的项是指使用一系列键检索存储在嵌套结构中的值。每个键对应于字典层次结构中的一个级别。
我们可以通过使用方括号直接索引或使用 get() 方法来实现这一点
示例:使用直接索引
在这种方法中,我们通过在方括号序列中指定每个键来访问嵌套字典中的值。序列中的每个键都引用嵌套字典中的一个级别,每个键都更深一个级别 -
# Define a nested dictionary
students = {
"Alice": {"age": 21, "major": "Computer Science"},
"Bob": {"age": 20, "major": "Engineering"},
"Charlie": {"age": 22, "major": "Mathematics"}
}
# Access Alice's major
alice_major = students["Alice"]["major"]
print("Alice's major:", alice_major)
# Access Bob's age
bob_age = students["Bob"]["age"]
print("Bob's age:", bob_age)
以下是上述代码的输出 -
Bob's age: 20
示例:使用 get() 方法
get() 方法用于获取与指定键关联的值。如果键不存在,则返回默认值(如果未指定,则为 None)-
# Define a nested dictionary
students = {
"Alice": {"age": 21, "major": "Computer Science"},
"Bob": {"age": 20, "major": "Engineering"},
"Charlie": {"age": 22, "major": "Mathematics"}
}
# Access Alice's major using .get()
alice_major = students.get("Alice", {}).get("major", "Not Found")
print("Alice's major:", alice_major)
# Safely access a non-existing key using .get()
dave_major = students.get("Dave", {}).get("major", "Not Found")
print("Dave's major:", dave_major)
上述代码的输出如下 -
Dave's major: Not Found
从嵌套字典中删除字典
我们可以使用 del 关键字从嵌套字典中删除字典。此关键字允许我们从嵌套字典中删除特定的键值对。
例在下面的示例中,我们使用 del 语句从 “students” 字典中删除 “Bob” 的嵌套字典 -
# Define a nested dictionary
students = {
"Alice": {"age": 21, "major": "Computer Science"},
"Bob": {"age": 20, "major": "Engineering"},
"Charlie": {"age": 22, "major": "Mathematics"}
}
# Delete the dictionary for Bob
del students["Bob"]
# Print the updated nested dictionary
print(students)
我们得到的输出如下所示 -
在 Python 中遍历嵌套字典
遍历嵌套字典是指在字典的每个级别循环遍历键和值。这允许您访问和操作嵌套结构中的项。
我们可以使用嵌套循环遍历嵌套字典。外部循环迭代主字典的键和值,而内循环迭代嵌套字典的键和值。
例在这个例子中,我们正在遍历 “students” 字典,通过遍历嵌套字典来检索每个学生的姓名及其相应的详细信息 -
# Defining a nested dictionary
students = {
"Alice": {"age": 21, "major": "Computer Science"},
"Bob": {"age": 20, "major": "Engineering"},
"Charlie": {"age": 22, "major": "Mathematics"}
}
# Iterating through the Nested Dictionary:
for student, details in students.items():
print(f"Student: {student}")
for key, value in details.items():
print(f" {key}: {value}")
获得的输出如下所示 -
age: 21
major: Computer Science
Student: Bob
age: 20
major: Engineering
Student: Charlie
age: 22
major: Mathematics