You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python递归解析带父级的扁平字典?实现实体属性继承

问题描述

我有一个存储实体的扁平字典,每个实体可指定父级。希望通过递归构建实体,遵循以下逻辑:

  • 每个实体继承父级的默认属性(如is_mammal)
  • 每个实体可覆盖父级的默认属性(如age)
  • 每个实体可添加新属性(如hobby)

附上代码示例及预期输出:

entities = {
    'human': {
        'is_mammal': True,
        'age': None,
    },
    'man': {
        'parent': 'human', 
        'gender': 'male',
    },
    'john': {
        'parent': 'man',
        'age': 20,
        'hobby': 'football',
    }
}

def get_character(key):
    # ... 递归逻辑待实现 ...
    return entity
    
john = get_character('john')
print(john)

预期输出:

{
    'is_mammal': True,  # 继承自human
    'gender': 'male',   # 继承自man
    'parent': 'man', 
    'age': 20,          # 覆盖父级值
    'hobby': 'football' # 新增属性
}
解决方案

核心逻辑是先递归获取父级的完整继承属性,再与当前实体属性合并,利用字典合并特性让当前属性覆盖父级同名属性。

完整代码实现:

entities = {
    'human': {
        'is_mammal': True,
        'age': None,
    },
    'man': {
        'parent': 'human', 
        'gender': 'male',
    },
    'john': {
        'parent': 'man',
        'age': 20,
        'hobby': 'football',
    }
}

def get_character(key):
    # 创建当前实体副本,避免修改原字典
    current_entity = entities[key].copy()
    # 检查是否存在父级,存在则递归获取父级完整属性
    if 'parent' in current_entity:
        parent_attrs = get_character(current_entity['parent'])
        # 合并属性:父级属性在前,当前属性在后,实现覆盖逻辑
        current_entity = {**parent_attrs, **current_entity}
    return current_entity

john = get_character('john')
# 格式化输出提升可读性
import json
print(json.dumps(john, indent=4, ensure_ascii=False))

运行后输出:

{
    "is_mammal": true,
    "age": 20,
    "gender": "male",
    "parent": "man",
    "hobby": "football"
}

逻辑说明

  1. 递归溯源父级:如果当前实体包含parent键,递归调用函数获取父级的完整继承链属性
  2. 属性覆盖规则:通过{**父级字典, **当前字典}的合并方式,让当前实体的同名属性自动覆盖父级属性
  3. 保护原数据:每次操作都创建实体副本,避免修改原始字典中的数据

内容的提问来源于stack exchange,提问作者Mr. B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:30:59