Python 嵌套词典完整指南
当需要在 Python 中组织复杂的分层数据时,嵌套词典是必不可少的。它们对于处理 JSON 数据、配置设置或任何具有多个级别的结构化数据特别有用。
了解嵌套词典
嵌套词典只是包含其他词典作为值的词典。下面是一个基本示例:
employee = {
'name': 'Sarah Chen',
'position': {
'title': 'Senior Developer',
'department': 'Engineering',
'details': {
'level': 'L5',
'team': 'Backend',
'skills': ['Python', 'Go', 'SQL']
}
}
}
访问和修改嵌套值
让我们看看处理嵌套数据的不同方法:
# Basic access using multiple keys
print(employee['position']['title']) # Output: Senior Developer
print(employee['position']['details']['level']) # Output: L5
# Modifying nested values
employee['position']['details']['level'] = 'L6'
employee['position']['details']['skills'].append('Rust')
# Adding new nested data
employee['position']['details']['project'] = {
'name': 'Atlas',
'role': 'Tech Lead'
}
使用 get() 进行安全访问
当使用嵌套字典时,使用 'get()' 有助于避免 KeyError 异常:
def get_nested_value(dict_obj, keys, default=None):
"""Safely get nested dictionary values."""
current = dict_obj
for key in keys:
if isinstance(current, dict):
current = current.get(key, default)
else:
return default
return current
# Usage
employee = {
'name': 'Sarah Chen',
'position': {
'title': 'Senior Developer'
}
}
# Safe access with multiple keys
print(get_nested_value(employee, ['position', 'title'])) # Output: Senior Developer
print(get_nested_value(employee, ['position', 'salary'], 'Not specified')) # Output: Not specified
真实示例
管理应用程序设置
app_config = {
'database': {
'main': {
'host': 'localhost',
'port': 5432,
'credentials': {
'user': 'admin',
'password': 'secret'
}
},
'replica': {
'host': 'replica.example.com',
'port': 5432,
'credentials': {
'user': 'reader',
'password': 'readonly'
}
}
},
'api': {
'endpoints': {
'users': '/api/v1/users',
'products': '/api/v1/products'
},
'rate_limits': {
'standard': 100,
'premium': 1000
}
}
}
def get_db_connection_string(db_type):
db = app_config['database'][db_type]
creds = db['credentials']
return f"postgresql://{creds['user']}:{creds['password']}@{db['host']}:{db['port']}"
print(get_db_connection_string('main'))
电子商务产品目录
class ProductCatalog:
def __init__(self):
self.catalog = {
'electronics': {
'smartphones': {
'iphone_12': {
'name': 'iPhone 12',
'price': 799.99,
'specs': {
'storage': '128GB',
'color': ['Black', 'White', 'Blue'],
'screen': '6.1 inch'
},
'stock': {
'warehouse_1': 50,
'warehouse_2': 30
}
}
}
}
}
def get_product_price(self, category, subcategory, product):
try:
return self.catalog[category][subcategory][product]['price']
except KeyError:
return None
def get_total_stock(self, category, subcategory, product):
try:
stock = self.catalog[category][subcategory][product]['stock']
return sum(stock.values())
except KeyError:
return 0
# Usage
catalog = ProductCatalog()
print(catalog.get_product_price('electronics', 'smartphones', 'iphone_12')) # Output: 799.99
print(catalog.get_total_stock('electronics', 'smartphones', 'iphone_12')) # Output: 80
使用 JSON 数据
处理 JSON 数据时,通常使用嵌套词典:
import json
# Loading nested JSON data
user_data = '''{
"user": {
"profile": {
"name": "John Doe",
"contact": {
"email": "john@example.com",
"phone": {
"home": "555-1234",
"work": "555-5678"
}
}
},
"preferences": {
"theme": "dark",
"notifications": {
"email": true,
"sms": false
}
}
}
}'''
# Parse JSON into nested dictionary
data = json.loads(user_data)
# Access and modify data
def update_user_preference(data, preference_path, new_value):
current = data
*path, final_key = preference_path.split('.')
for key in path:
current = current.setdefault(key, {})
current[final_key] = new_value
return data
# Update a nested preference
update_user_preference(data, 'user.preferences.notifications.sms', True)
合并嵌套词典
这是一个合并嵌套词典的函数,可用于合并配置文件:
def deep_merge(dict1, dict2):
"""Merge two dictionaries recursively."""
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
# Example usage
defaults = {
'settings': {
'debug': False,
'logging': {
'level': 'INFO',
'format': 'standard'
}
}
}
user_settings = {
'settings': {
'logging': {
'level': 'DEBUG'
}
}
}
final_settings = deep_merge(defaults, user_settings)
print(final_settings)
常见模式和解决方案
创建默认嵌套结构
from collections import defaultdict
def nested_dict():
"""Create an infinitely nested defaultdict."""
return defaultdict(nested_dict)
# Usage
stats = nested_dict()
stats['2024']['Q1']['sales'] = 1000
stats['2024']['Q1']['costs'] = 800
# No KeyError even for non-existent paths
print(stats['2024']['Q1']['profit']) # Output: defaultdict
扁平化嵌套词典
有时你需要将嵌套字典转换为平面结构:
def flatten_dict(d, parent_key='', sep='_'):
"""Convert nested dictionary to flat structure."""
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key, sep).items())
else:
items.append((new_key, v))
return dict(items)
# Example
nested = {
'user': {
'name': 'Alice',
'address': {
'street': '123 Main St',
'city': 'Boston'
}
}
}
flat = flatten_dict(nested)
print(flat)
# Output: {'user_name': 'Alice', 'user_address_street': '123 Main St', 'user_address_city': 'Boston'}
嵌套字典是在 Python 中组织复杂数据的基本工具。通过了解如何有效地创建、访问和作它们,您可以构建更有条理和可维护的代码。
请记住,在使用深度嵌套结构时,请始终考虑错误处理并使用适当的帮助程序函数,以使您的代码更加健壮和可读。