Python 简明教程
Python - Nested Dictionaries
Nested Dictionaries
Python 中的嵌套字典是指存储在另一个 dictionary 中的字典。换句话说,一个字典可以包含其他字典作为其值,形成层次结构或嵌套结构。
Nested dictionaries in Python refer to dictionaries that are stored as values within another dictionary. In other words, a dictionary can contain other dictionaries as its values, forming a hierarchical or nested structure.
可以像修改普通字典一样修改、更新或扩展嵌套字典。可以在嵌套结构的任何级别添加、删除或更新键值对。
Nested dictionaries can be modified, updated, or extended in the same way as regular dictionaries. You can add, remove, or update key-value pairs at any level of the nested structure.
Creating a Nested Dictionary in Python
可以通过定义字典(某些键的值本身是字典)来创建 Python 中的嵌套字典。这允许创建分层结构,其中每个键值对表示一个嵌套信息的级别。这可以通过多种方式实现−
We can create a nested dictionary in Python by defining a dictionary where the values of certain keys are themselves dictionaries. This allows for the creation of a hierarchical structure where each key-value pair represents a level of nested information. This can be achieved in several ways −
Example: Direct Assignment
采用这种方法,我们可以直接在单字典定义中将字典分配为外部键的值 −
In this approach, we can directly assign dictionaries as values to outer keys within a single dictionary definition −
# 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)
Example: Using a Loop
采用这种方法,先初始化一个空外部字典,然后使用循环填充字典作为值,以定义嵌套字典 −
With this method, an empty outer dictionary is initialized, and then populated with dictionaries as values using a loop to define nested dictionaries −
# 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)
Adding Items to a Nested Dictionary in Python
创建嵌套字典后,我们可以通过使用键访问特定的嵌套字典,然后为其分配新的键值对,向其中添加项目。
Once a nested dictionary is created, we can add items to it by accessing the specific nested dictionary using its key and then assigning a new key-value pair to it.
Example
在以下示例中,我们将定义一个嵌套字典 "students",其中每个键表示学生的姓名,其值是另一个包含学生详细信息的字典。
In the following example, we are defining a nested dictionary "students" where each key represents a student’s name and its value is another dictionary containing details about the student.
接下来,我们在 Alice 的嵌套字典中添加一个新的键值对,然后为新学生 Charlie 添加一个新的嵌套字典 −
Then, we add a new key-value pair to Alice’s nested dictionary and add a new nested dictionary for a new student, 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)
它将生成如下输出:
It will produce the following output −
{'Alice': {'age': 21, 'major': 'Computer Science', 'GPA': 3.8}, 'Bob': {'age': 20, 'major': 'Engineering'}, 'Charlie': {'age': 22, 'major': 'Mathematics'}}
Accessing Items of a Nested Dictionary in Python
在 Python 中访问嵌套字典中的项是指使用一系列键值来检索存储在嵌套结构中的值。每个键值对应字典层次结构中的一个级别。
Accessing items of a nested dictionary in Python refers to retrieving values stored within the nested structure by using a series of keys. Each key corresponds to a level in the hierarchy of the dictionary.
我们可以通过使用方括号直接索引或使用 get() 方法来实现此目的 −
We can achieve this through direct indexing with square brackets or by using the get() method
Example: Using Direct Indexing
在此方法中,我们通过在方括号序列中指定每个键值来访问嵌套字典中的值。序列中的每个键值引用嵌套字典中的一个级别,并且随着每个键值的深入而深入一个级别 −
In this approach, we access values in a nested dictionary by specifying each key in a sequence of square brackets. Each key in the sequence refers to a level in the nested dictionary, progressing one level deeper with each key −
# 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)
以下是上面代码的输出: -
Following is the output of the above code −
Alice's major: Computer Science
Bob's age: 20
Example: Using the get() Method
get() 方法用于获取与指定键值关联的值。如果不存在键值,它将返回一个默认值(如果没有指定,则为 None) −
The get() method is used to fetch the value associated with the specified key. If the key does not exist, it returns a default value (which is None if not specified) −
# 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)
上述代码的输出如下:
Output of the above code is as follows −
Alice's major: Computer Science
Dave's major: Not Found
Deleting a Dictionary from a Nested Dictionary
我们可以使用 del 关键字从嵌套字典中删除字典。此关键字允许我们从嵌套字典中删除一个特定的键值对。
We can delete dictionaries from a nested dictionary by using the del keyword. This keyword allows us to remove a specific key-value pair from the nested dictionary.
Example
在以下示例中,我们使用 del 语句从“students”字典中删除“Bob”的嵌套字典 −
In the following example, we delete the nested dictionary for "Bob" from "students" dictionary using the del statement −
# 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)
我们得到了如下输出 −
We get the output as shown below −
{'Alice': {'age': 21, 'major': 'Computer Science'}, 'Charlie': {'age': 22, 'major': 'Mathematics'}}
Iterating Through a Nested Dictionary in Python
遍历嵌套字典是指循环遍历字典中每个级别的键值。这允许您访问和处理嵌套结构中的项。
Iterating through a nested dictionary refers to looping through the keys and values at each level of the dictionary. This allows you to access and manipulate items within the nested structure.
我们可以使用嵌套循环来遍历嵌套字典。外部循环迭代主字典的键值,而内部循环迭代嵌套字典的键值。
We can iterate through a nested dictionary by using nested loops. The outer loop iterates over the keys and values of the main dictionary, while the inner loop iterates over the keys and values of the nested dictionaries.
Example
在此示例中,我们遍历“students”字典,通过迭代嵌套字典检索每个学生的名字及其对应的详细信息 −
In this example, we are iterating through the "students" dictionary, retrieving each student’s name and their corresponding details by iterating through the nested dictionaries −
# 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}")
获得的输出如下所示 −
The output obtained is as shown below −
Student: Alice
age: 21
major: Computer Science
Student: Bob
age: 20
major: Engineering
Student: Charlie
age: 22
major: Mathematics