Skip to content
Advertisement

Python: how parse this dict recursively?

I’ve a flat dict with entities. Each entity can have a parent. I’d like to recursively build each entity, considering the parent values.

Logic:

  1. Each entity inherits defaults from its parent (e.g. is_mammal)
  2. Each entity can overwrite the defaults of its parent (e.g. age)
  3. Each entity can add new attributes (e.g. hobby)

I’m struggling to get it done. Help is appreciated, thanks!

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

def get_character(key):
    # ... recursive magic with entities ...
    return entity
    
john = get_character('john')
print(john)

Expected output:

{
    'is_mammal': True,  # inherited from human
    'gender': 'male'  # inherited from man
    'parent': 'man', 
    'age': 20, # overwritten
    'hobby': 'football', # added
}

Advertisement

Answer

def get_character(entities, key):
    try:
        entity = get_character(entities, entities[key]['parent'])
    except KeyError:
        entity = {}
    entity.update(entities[key])
    return entity
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement