Python 嵌套词典完整指南

liftword2个月前 (03-07)技术文章16

当需要在 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 为我们提供了多种合并字典的方式,每种方式都有其独特的应用场景。探索 Py...

现代化python字典合并的技巧

现代Python字典合并:使用|运算符在Python 3.9之前,有两种常见的合并字典的方法:使用update方法或**运算符。然而,这两种方法都有其缺点。在本文中,我们将探讨Python中合并字典的...

python将两个字典进行合并的方法

在 Python 中,可以使用 update() 方法将一个字典合并到另一个字典中,也可以使用运算符 | 或 ** 将两个字典合并为一个新的字典。以下是示例代码,演示了三种不同的方式来合并字典:# 定...

Python 字典合并、求和大作战,轻松搞定各路数据

在使用 Python 采集来自不同渠道的数据,很多都是以字典的形式存储。将它们合并、处理是经常使用的进本操作,在本文中,我们将介绍多种合并和求和字典的方法。合并词典是指涉及将多个词典中的键值对合并到一...

Python 字典(Dictionary):高效数据映射的强大工具

在 Python 中,字典是一种基于键值对(key-value pairs)的数据结构,能够高效地进行数据映射(data mapping)和快速查找(efficient lookup)。字典以无序(u...