Python 嵌套词典完整指南

liftword3个月前 (03-07)技术文章25

当需要在 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 中组织复杂数据的基本工具。通过了解如何有效地创建、访问和作它们,您可以构建更有条理和可维护的代码。

请记住,在使用深度嵌套结构时,请始终考虑错误处理并使用适当的帮助程序函数,以使您的代码更加健壮和可读。

相关文章

一文掌握Python的字典

字典是 Python 中最强大、最灵活的内置数据结构之一。它们允许存储键值对,从而实现高效的数据检索、操作和组织。本文深入探讨了字典,涵盖了它们的创建、操作和高级用法,以帮助中级 Python 开发人...

python 元组转字典

在 Python 中,可以使用内置函数 zip() 将两个序列合并成一个字典。元组可以看作是不可变的序列,因此可以将元组作为输入序列传递给 zip() 函数,以将其转换为字典。假设我们有两个元组,一个...

一文讲清Python找到与字典相关的常用函数

创建字典建立一个新字典:# A tome of elements and their symbols elements = {'Hydrogen': 'H', 'Helium': 'He', 'Lit...

深入了解Python字典的高级用法-1

Python字典是一种强大的数据结构,不仅仅用于存储和访问数据。本文将介绍一些高级的字典用法,包括字典推导、嵌套字典、默认字典、字典合并等,以帮助您更好地利用Python字典进行编程。1. 字典推导(...

Python字典核心秘籍:从键值对到嵌套结构,20+实战案例轻松掌握

Python字典(Dictionary)知识点教程一、字典的定义与特性定义:字典是可变的、无序的键值对集合,用花括号 {} 定义,键值对用 键: 值 表示。person = {"name": "Ali...

Python 中没人告诉你的10个酷炫功能

Python 是一种强调简洁和可读性的语言,但其干净的语法之下隐藏着丰富的强大且不太为人所知的特性。许多开发者,即使是经验丰富的开发者,也常常忽视这些宝石,它们可以帮助简化代码、提高效率,并使编程更加...