7.1 创建嵌套字典
嵌套字典是描述复杂数据结构的一种非常方便的方法,你会经常遇到。让我们练习一下创建它们。
创建嵌套字典
这是创建嵌套字典的一个示例:
person = {
"name": "Alice",
"details": {
"age": 25,
"city": "New York",
"address": {
"street": "123 Main St",
"zip": "10001"
},
"mother": "Jane Smith"
},
"gender": "female"
}
print(person) # 输出: {'name': 'Alice', 'details': {'age': 25, 'city': 'New York', 'address': {'street': '123 Main St', 'zip': '10001'}, 'mother': 'Jane Smith'}, 'gender': 'female'}
在这个例子中,person 是一个字典,包含嵌套字典 details,而 details 又包含另一个嵌套字典 address。
嵌套字典也可以从片段中创建:
address = {
"street": "123 Main St",
"zip": "10001"
}
details = {
"age": 25,
"city": "New York",
"address": address
}
person = {
"name": "Alice",
"details": details,
"gender": "female"
}
print(person) # 输出: {'name': 'Alice', 'details': {'age': 25, 'city': 'New York', 'address': {'street': '123 Main St', 'zip': '10001'}}, 'gender': 'female'}
7.2 访问嵌套字典元素
访问嵌套字典中的元素很简单明了。以下是操作步骤:
访问顶层元素
name = person["name"]
print(name) # 输出: Alice
访问嵌套字典的元素
age = person["details"]["age"]
city = person["details"]["city"]
print(age) # 输出: 25
print(city) # 输出: New York
访问更深层次的嵌套元素
street = person["details"]["address"]["street"]
zip_code = person["details"]["address"]["zip"]
print(street) # 输出: 123 Main St
print(zip_code) # 输出: 10001
7.3 修改嵌套字典的元素
如果你已经知道如何输出任何嵌套程度的元素,那么更改它们会更容易:
更改顶层的值
person["name"] = "Bob"
print(person["name"]) # 输出: Bob
更改嵌套字典的值
person["details"]["age"] = 26
print(person["details"]["age"]) # 输出: 26
更改更深层次的嵌套值
person["details"]["address"]["city"] = "Los Angeles"
print(person["details"]["address"]["city"]) # 输出: Los Angeles
向嵌套字典添加新元素
person["details"]["phone"] = "123-456-7890"
print(person["details"]["phone"]) # 输出: 123-456-7890
删除顶层元素
# 从字典 'person' 删除元素 'country'
del person["country"]
print(person) # 'country' 将从字典中删除
删除嵌套字典中的元素
# 从字典 'details' 删除元素 'phone'
del person["details"]["phone"]
print(person["details"]) # 'phone' 将从字典 'details' 中删除
7.4 遍历嵌套字典
有几种方法可以遍历字典中的所有元素。循环是最简单的方法:
遍历嵌套字典的元素
for key, value in person.items(): # 遍历父字典
if isinstance(value, dict): # 如果值是一个字典
for key2, value2 in value.items(): # 遍历子字典的元素
print(f"{key} --> {key2}: {value2}")
递归遍历所有嵌套层次
def print_dict(d, indent=0):
for key, value in d.items():
print(" " * indent + str(key) + ": ", end="")
if isinstance(value, dict):
print()
print_dict(value, indent + 1)
else:
print(value)
print_dict(person)
你将在“算法和数据结构”章节中了解更多关于递归的内容。
顺便说一下,递归在查找深层嵌套字典中的值时很方便。这里有个例子:
def find_key(d, key):
if key in d:
return d[key]
for k, v in d.items():
if isinstance(v, dict):
result = find_key(v, key)
if result:
return result
return None
phone = find_key(person, "phone")
print(phone) # 输出: None (因为元素 'phone' 已被删除)
GO TO FULL VERSION